Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "net/http"
- "github.com/jkrovnl/rkods/controllers"
- "github.com/jkrovnl/rkods/models"
- "github.com/jkrovnl/rkods/session"
- )
- func main() {
- uc := controllers.NewUserController(models.TPL)
- http.HandleFunc("/", uc.Index)
- http.HandleFunc("/one", uc.One)
- http.HandleFunc("/signup", uc.Signup)
- http.HandleFunc("/login", uc.Login)
- http.HandleFunc("/logout", session.Logout)
- http.HandleFunc("/checkusername", controllers.CheckUsername)
- http.Handle("/favicon.ico", http.NotFoundHandler())
- http.ListenAndServe(":8080", nil)
- }
- ==================================================================================
- package controllers //controllers/controllers.go
- import (
- "fmt"
- "html/template"
- "io/ioutil"
- "log"
- "net/http"
- "time"
- "github.com/jkrovnl/rkods/models"
- "github.com/jkrovnl/rkods/session"
- uuid "github.com/satori/go.uuid"
- "golang.org/x/crypto/bcrypt"
- )
- type UserController struct {
- tpl *template.Template
- }
- func NewUserController(tpl *template.Template) *UserController {
- return &UserController{tpl}
- }
- func (uc UserController) Login(w http.ResponseWriter, req *http.Request) {
- if session.AlreadyLoggedIn(w, req) {
- http.Redirect(w, req, "/", http.StatusSeeOther)
- return
- }
- if req.Method == http.MethodPost {
- un := req.FormValue("username")
- p := req.FormValue("password")
- s, ok := models.DbUser[un]
- if !ok {
- http.Error(w, "username nav", 403)
- return
- }
- err := bcrypt.CompareHashAndPassword(s.Password, []byte(p))
- if err != nil {
- http.Error(w, "password nav", 403)
- return
- }
- sID, err := uuid.NewV4()
- if err != nil {
- log.Fatalln(err)
- }
- c := &http.Cookie{
- Name: "session",
- Value: sID.String(),
- MaxAge: models.SessionLength,
- }
- http.SetCookie(w, c)
- models.DbSession[c.Value] = models.Session{un, time.Now()}
- http.Redirect(w, req, "/", http.StatusSeeOther)
- }
- uc.tpl.ExecuteTemplate(w, "login.gohtml", nil)
- }
- func (uc UserController) Index(w http.ResponseWriter, req *http.Request) {
- u := session.GetUser(w, req)
- uc.tpl.ExecuteTemplate(w, "index.gohtml", u)
- }
- func (uc UserController) One(w http.ResponseWriter, req *http.Request) {
- u := session.GetUser(w, req)
- if !session.AlreadyLoggedIn(w, req) {
- http.Redirect(w, req, "/", 303)
- return
- } else if u.Role != "admin" {
- http.Error(w, "jabut adminam", 403)
- return
- }
- uc.tpl.ExecuteTemplate(w, "one.gohtml", u)
- }
- func (uc UserController) Signup(w http.ResponseWriter, r *http.Request) {
- if session.AlreadyLoggedIn(w, r) {
- http.Redirect(w, r, "/", 303)
- return
- }
- if r.Method == http.MethodPost {
- un := r.FormValue("username")
- p := r.FormValue("password")
- rl := r.FormValue("role")
- _, ok := models.DbUser[un]
- if ok {
- http.Error(w, "username aiznemts", 403)
- return
- }
- bs, err := bcrypt.GenerateFromPassword([]byte(p), bcrypt.MinCost)
- if err != nil {
- log.Fatalln(err)
- }
- sID, err := uuid.NewV4()
- if err != nil {
- log.Fatalln(err)
- }
- c := &http.Cookie{
- Name: "session",
- Value: sID.String(),
- MaxAge: models.SessionLength,
- }
- http.SetCookie(w, c)
- u := models.User{un, bs, rl}
- models.DbSession[c.Value] = models.Session{un, time.Now()}
- models.DbUser[un] = u
- http.Redirect(w, r, "/", 303)
- }
- uc.tpl.ExecuteTemplate(w, "signup.gohtml", nil)
- }
- func CheckUsername(w http.ResponseWriter, req *http.Request) {
- sampleUsers := map[string]bool{
- "krovn": true,
- "jkrovnl": true,
- "admin": true,
- }
- bs, err := ioutil.ReadAll(req.Body)
- if err != nil {
- fmt.Println(err)
- }
- sbs := string(bs)
- fmt.Println("USERNAME: ", sbs)
- fmt.Fprint(w, sampleUsers[sbs])
- }
- ==================================================================================
- package session // session/session.go
- import (
- "log"
- "net/http"
- "time"
- "github.com/jkrovnl/rkods/models"
- uuid "github.com/satori/go.uuid"
- )
- func GetUser(w http.ResponseWriter, req *http.Request) models.User {
- c, err := req.Cookie("session")
- if err != nil {
- sID, err := uuid.NewV4()
- if err != nil {
- log.Fatalln(err)
- }
- c = &http.Cookie{
- Name: "session",
- Value: sID.String(),
- }
- }
- c.MaxAge = models.SessionLength
- http.SetCookie(w, c)
- var u models.User
- if s, ok := models.DbSession[c.Value]; ok {
- s.LastActivity = time.Now()
- models.DbSession[c.Value] = s
- u = models.DbUser[s.Un]
- }
- return u
- }
- func AlreadyLoggedIn(w http.ResponseWriter, req *http.Request) bool {
- c, err := req.Cookie("session")
- if err != nil {
- return false
- }
- c.MaxAge = models.SessionLength
- http.SetCookie(w, c)
- s, ok := models.DbSession[c.Value]
- if ok {
- s.LastActivity = time.Now()
- models.DbSession[c.Value] = s
- }
- _, ok = models.DbUser[s.Un]
- return ok
- }
- func Logout(w http.ResponseWriter, req *http.Request) {
- if !AlreadyLoggedIn(w, req) {
- http.Redirect(w, req, "/", http.StatusSeeOther)
- return
- }
- c, _ := req.Cookie("session")
- delete(models.DbSession, c.Value)
- c = &http.Cookie{
- Name: "session",
- Value: "",
- MaxAge: -1,
- }
- http.SetCookie(w, c)
- if time.Now().Sub(models.DbSessionCleaned) > (30 * time.Second) {
- go cleanSession()
- }
- http.Redirect(w, req, "/", http.StatusSeeOther)
- }
- func cleanSession() {
- for k, v := range models.DbSession {
- if time.Now().Sub(v.LastActivity) > (30 * time.Second) {
- delete(models.DbSession, k)
- }
- }
- }
- ==================================================================================
- package models // models.models.go
- import (
- "html/template"
- "time"
- "golang.org/x/crypto/bcrypt"
- )
- var TPL *template.Template
- var DbSession = map[string]Session{}
- var DbUser = map[string]User{}
- var DbSessionCleaned time.Time
- const SessionLength int = 30
- type User struct {
- Username string
- Password []byte
- Role string
- }
- type Session struct {
- Un string
- LastActivity time.Time
- }
- func init() {
- TPL = template.Must(template.ParseGlob("templates/*.gohtml"))
- bs, _ := bcrypt.GenerateFromPassword([]byte("!E14ffort"), bcrypt.MinCost)
- ns, _ := bcrypt.GenerateFromPassword([]byte("nauda100"), bcrypt.MinCost)
- DbUser["admin"] = User{"admin", ns, "admin"}
- DbUser["krovn"] = User{"krovn", bs, "user"}
- DbSessionCleaned = time.Now()
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement