Advertisement
Guest User

Untitled

a guest
Dec 20th, 2016
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. func login(w http.ResponseWriter, r *http.Request) {
  2.  
  3. name := r.FormValue("uname")
  4. pass := r.FormValue("password")
  5.  
  6. setSession(&User{Username: name, Password: pass}, w) //deploys cookie.
  7. rTarget := "/"
  8. if name != "" && pass != "" {
  9. if getCookieState(r) { //checks database and returns a bool
  10. rTarget = "/example"
  11. }
  12. }
  13. http.Redirect(w, r, rTarget, 302)
  14. }
  15.  
  16. func setSession(u *User, w http.ResponseWriter) {
  17. if userExists(u) { //checks database and returns bool if user/pass is in there.
  18. value := map[string]string{
  19. "name": u.Username,
  20. "pass": u.Password,
  21. "cookie": "true",
  22. }
  23. if encoded, err := cookieHandler.Encode("session", value); err == nil {
  24. cookie := &http.Cookie{
  25. Name: "session",
  26. Value: encoded,
  27. Path: "/",
  28. }
  29. http.SetCookie(w, cookie)
  30. }
  31. }
  32. }
  33.  
  34. func getCookieState(r *http.Request) (v bool) {
  35. if cookie, err := r.Cookie("session"); err == nil {
  36. cookieValue := make(map[string]string)
  37. if err = cookieHandler.Decode("session", cookie.Value, &cookieValue); err == nil {
  38. value := cookieValue["cookie"]
  39. v, _ = strconv.ParseBool(value)
  40. }
  41. }
  42. if v {
  43. return true
  44. }
  45. return false
  46. }
  47.  
  48. func userExists(u *User) bool {
  49. var db, _ = sql.Open("sqlite3", "user.sqlite3")
  50. defer db.Close()
  51. var us, ps string
  52. q, err := db.Query("select username, password from users where username = '" + u.Username + "' and password = '" + u.Password + "'")
  53. if err != nil {
  54. return false
  55. }
  56. for q.Next() {
  57. q.Scan(&us, &ps)
  58. }
  59. if us == u.Username && ps == u.Password {
  60. return true
  61. }
  62. return false
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement