Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func login(w http.ResponseWriter, r *http.Request) {
- name := r.FormValue("uname")
- pass := r.FormValue("password")
- setSession(&User{Username: name, Password: pass}, w) //deploys cookie.
- rTarget := "/"
- if name != "" && pass != "" {
- if getCookieState(r) { //checks database and returns a bool
- rTarget = "/example"
- }
- }
- http.Redirect(w, r, rTarget, 302)
- }
- func setSession(u *User, w http.ResponseWriter) {
- if userExists(u) { //checks database and returns bool if user/pass is in there.
- value := map[string]string{
- "name": u.Username,
- "pass": u.Password,
- "cookie": "true",
- }
- if encoded, err := cookieHandler.Encode("session", value); err == nil {
- cookie := &http.Cookie{
- Name: "session",
- Value: encoded,
- Path: "/",
- }
- http.SetCookie(w, cookie)
- }
- }
- }
- func getCookieState(r *http.Request) (v bool) {
- if cookie, err := r.Cookie("session"); err == nil {
- cookieValue := make(map[string]string)
- if err = cookieHandler.Decode("session", cookie.Value, &cookieValue); err == nil {
- value := cookieValue["cookie"]
- v, _ = strconv.ParseBool(value)
- }
- }
- if v {
- return true
- }
- return false
- }
- func userExists(u *User) bool {
- var db, _ = sql.Open("sqlite3", "user.sqlite3")
- defer db.Close()
- var us, ps string
- q, err := db.Query("select username, password from users where username = '" + u.Username + "' and password = '" + u.Password + "'")
- if err != nil {
- return false
- }
- for q.Next() {
- q.Scan(&us, &ps)
- }
- if us == u.Username && ps == u.Password {
- return true
- }
- return false
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement