Advertisement
krovn

Untitled

Nov 5th, 2019
805
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 6.20 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "net/http"
  5.  
  6.     "github.com/jkrovnl/rkods/controllers"
  7.     "github.com/jkrovnl/rkods/models"
  8.     "github.com/jkrovnl/rkods/session"
  9. )
  10.  
  11. func main() {
  12.     uc := controllers.NewUserController(models.TPL)
  13.     http.HandleFunc("/", uc.Index)
  14.     http.HandleFunc("/one", uc.One)
  15.     http.HandleFunc("/signup", uc.Signup)
  16.     http.HandleFunc("/login", uc.Login)
  17.     http.HandleFunc("/logout", session.Logout)
  18.     http.HandleFunc("/checkusername", controllers.CheckUsername)
  19.     http.Handle("/favicon.ico", http.NotFoundHandler())
  20.     http.ListenAndServe(":8080", nil)
  21. }
  22. ==================================================================================
  23. package controllers //controllers/controllers.go
  24.  
  25. import (
  26.     "fmt"
  27.     "html/template"
  28.     "io/ioutil"
  29.     "log"
  30.     "net/http"
  31.     "time"
  32.  
  33.     "github.com/jkrovnl/rkods/models"
  34.     "github.com/jkrovnl/rkods/session"
  35.     uuid "github.com/satori/go.uuid"
  36.     "golang.org/x/crypto/bcrypt"
  37. )
  38.  
  39. type UserController struct {
  40.     tpl *template.Template
  41. }
  42.  
  43. func NewUserController(tpl *template.Template) *UserController {
  44.     return &UserController{tpl}
  45. }
  46.  
  47. func (uc UserController) Login(w http.ResponseWriter, req *http.Request) {
  48.     if session.AlreadyLoggedIn(w, req) {
  49.         http.Redirect(w, req, "/", http.StatusSeeOther)
  50.         return
  51.     }
  52.     if req.Method == http.MethodPost {
  53.         un := req.FormValue("username")
  54.         p := req.FormValue("password")
  55.         s, ok := models.DbUser[un]
  56.         if !ok {
  57.             http.Error(w, "username nav", 403)
  58.             return
  59.         }
  60.         err := bcrypt.CompareHashAndPassword(s.Password, []byte(p))
  61.         if err != nil {
  62.             http.Error(w, "password nav", 403)
  63.             return
  64.         }
  65.         sID, err := uuid.NewV4()
  66.         if err != nil {
  67.             log.Fatalln(err)
  68.         }
  69.         c := &http.Cookie{
  70.             Name:   "session",
  71.             Value:  sID.String(),
  72.             MaxAge: models.SessionLength,
  73.         }
  74.         http.SetCookie(w, c)
  75.         models.DbSession[c.Value] = models.Session{un, time.Now()}
  76.         http.Redirect(w, req, "/", http.StatusSeeOther)
  77.     }
  78.     uc.tpl.ExecuteTemplate(w, "login.gohtml", nil)
  79. }
  80.  
  81. func (uc UserController) Index(w http.ResponseWriter, req *http.Request) {
  82.     u := session.GetUser(w, req)
  83.     uc.tpl.ExecuteTemplate(w, "index.gohtml", u)
  84. }
  85.  
  86. func (uc UserController) One(w http.ResponseWriter, req *http.Request) {
  87.     u := session.GetUser(w, req)
  88.     if !session.AlreadyLoggedIn(w, req) {
  89.         http.Redirect(w, req, "/", 303)
  90.         return
  91.     } else if u.Role != "admin" {
  92.         http.Error(w, "jabut adminam", 403)
  93.         return
  94.     }
  95.     uc.tpl.ExecuteTemplate(w, "one.gohtml", u)
  96. }
  97.  
  98. func (uc UserController) Signup(w http.ResponseWriter, r *http.Request) {
  99.     if session.AlreadyLoggedIn(w, r) {
  100.         http.Redirect(w, r, "/", 303)
  101.         return
  102.     }
  103.     if r.Method == http.MethodPost {
  104.         un := r.FormValue("username")
  105.         p := r.FormValue("password")
  106.         rl := r.FormValue("role")
  107.         _, ok := models.DbUser[un]
  108.         if ok {
  109.             http.Error(w, "username aiznemts", 403)
  110.             return
  111.         }
  112.         bs, err := bcrypt.GenerateFromPassword([]byte(p), bcrypt.MinCost)
  113.         if err != nil {
  114.             log.Fatalln(err)
  115.         }
  116.         sID, err := uuid.NewV4()
  117.         if err != nil {
  118.             log.Fatalln(err)
  119.         }
  120.         c := &http.Cookie{
  121.             Name:   "session",
  122.             Value:  sID.String(),
  123.             MaxAge: models.SessionLength,
  124.         }
  125.         http.SetCookie(w, c)
  126.         u := models.User{un, bs, rl}
  127.         models.DbSession[c.Value] = models.Session{un, time.Now()}
  128.         models.DbUser[un] = u
  129.         http.Redirect(w, r, "/", 303)
  130.     }
  131.     uc.tpl.ExecuteTemplate(w, "signup.gohtml", nil)
  132. }
  133.  
  134. func CheckUsername(w http.ResponseWriter, req *http.Request) {
  135.     sampleUsers := map[string]bool{
  136.         "krovn":   true,
  137.         "jkrovnl": true,
  138.         "admin":   true,
  139.     }
  140.     bs, err := ioutil.ReadAll(req.Body)
  141.     if err != nil {
  142.         fmt.Println(err)
  143.     }
  144.     sbs := string(bs)
  145.     fmt.Println("USERNAME: ", sbs)
  146.     fmt.Fprint(w, sampleUsers[sbs])
  147. }
  148. ==================================================================================
  149. package session // session/session.go
  150.  
  151. import (
  152.     "log"
  153.     "net/http"
  154.     "time"
  155.  
  156.     "github.com/jkrovnl/rkods/models"
  157.     uuid "github.com/satori/go.uuid"
  158. )
  159.  
  160. func GetUser(w http.ResponseWriter, req *http.Request) models.User {
  161.     c, err := req.Cookie("session")
  162.     if err != nil {
  163.         sID, err := uuid.NewV4()
  164.         if err != nil {
  165.             log.Fatalln(err)
  166.         }
  167.         c = &http.Cookie{
  168.             Name:  "session",
  169.             Value: sID.String(),
  170.         }
  171.     }
  172.     c.MaxAge = models.SessionLength
  173.     http.SetCookie(w, c)
  174.     var u models.User
  175.     if s, ok := models.DbSession[c.Value]; ok {
  176.         s.LastActivity = time.Now()
  177.         models.DbSession[c.Value] = s
  178.         u = models.DbUser[s.Un]
  179.     }
  180.     return u
  181. }
  182.  
  183. func AlreadyLoggedIn(w http.ResponseWriter, req *http.Request) bool {
  184.     c, err := req.Cookie("session")
  185.     if err != nil {
  186.         return false
  187.     }
  188.     c.MaxAge = models.SessionLength
  189.     http.SetCookie(w, c)
  190.     s, ok := models.DbSession[c.Value]
  191.     if ok {
  192.         s.LastActivity = time.Now()
  193.         models.DbSession[c.Value] = s
  194.     }
  195.     _, ok = models.DbUser[s.Un]
  196.     return ok
  197. }
  198.  
  199. func Logout(w http.ResponseWriter, req *http.Request) {
  200.     if !AlreadyLoggedIn(w, req) {
  201.         http.Redirect(w, req, "/", http.StatusSeeOther)
  202.         return
  203.     }
  204.     c, _ := req.Cookie("session")
  205.     delete(models.DbSession, c.Value)
  206.     c = &http.Cookie{
  207.         Name:   "session",
  208.         Value:  "",
  209.         MaxAge: -1,
  210.     }
  211.     http.SetCookie(w, c)
  212.     if time.Now().Sub(models.DbSessionCleaned) > (30 * time.Second) {
  213.         go cleanSession()
  214.     }
  215.     http.Redirect(w, req, "/", http.StatusSeeOther)
  216. }
  217.  
  218. func cleanSession() {
  219.     for k, v := range models.DbSession {
  220.         if time.Now().Sub(v.LastActivity) > (30 * time.Second) {
  221.             delete(models.DbSession, k)
  222.         }
  223.     }
  224. }
  225.  
  226. ==================================================================================
  227. package models // models.models.go
  228.  
  229. import (
  230.     "html/template"
  231.     "time"
  232.  
  233.     "golang.org/x/crypto/bcrypt"
  234. )
  235.  
  236. var TPL *template.Template
  237. var DbSession = map[string]Session{}
  238. var DbUser = map[string]User{}
  239. var DbSessionCleaned time.Time
  240.  
  241. const SessionLength int = 30
  242.  
  243. type User struct {
  244.     Username string
  245.     Password []byte
  246.     Role     string
  247. }
  248. type Session struct {
  249.     Un           string
  250.     LastActivity time.Time
  251. }
  252.  
  253. func init() {
  254.     TPL = template.Must(template.ParseGlob("templates/*.gohtml"))
  255.     bs, _ := bcrypt.GenerateFromPassword([]byte("!E14ffort"), bcrypt.MinCost)
  256.     ns, _ := bcrypt.GenerateFromPassword([]byte("nauda100"), bcrypt.MinCost)
  257.     DbUser["admin"] = User{"admin", ns, "admin"}
  258.     DbUser["krovn"] = User{"krovn", bs, "user"}
  259.     DbSessionCleaned = time.Now()
  260. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement