123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- package main
-
- import (
- "crypto/rand"
- "encoding/base64"
- "errors"
- "log"
- "net/http"
- "time"
- )
-
- type SessionData struct {
- username string
- }
-
- var (
- sessions = make(map[string]*SessionData)
- )
-
- func userOk(username, password string) bool {
- return (username == "Lamperi" && password == "paskaa")
- }
-
- func tryLogin(username, password string, longerTime bool) (http.Cookie, error) {
- if exists := userOk(username, password); !exists {
- return http.Cookie{},
- errors.New("The username or password you entered isn't correct.")
- }
-
- sid, err := randString(32)
- if err != nil {
- return http.Cookie{}, err
- }
-
- sessions[sid] = &SessionData{username}
-
- hours := time.Duration(1)
- if longerTime {
- hours = time.Duration(336)
- }
-
- loginCookie := http.Cookie{
- Name: "id",
- Value: sid,
- MaxAge: int((time.Hour * hours).Seconds()),
- HttpOnly: true,
- }
-
- return loginCookie, nil
- }
-
- func getSession(req *http.Request) (*SessionData, error) {
- cookie, err := req.Cookie("id")
- if err != nil {
- return nil, err
- }
-
- session, exists := sessions[cookie.Value]
- if !exists {
- return nil, errors.New("Session expired from server")
- }
- return session, nil
- }
-
- func randString(size int) (string, error) {
- buf := make([]byte, size)
-
- if _, err := rand.Read(buf); err != nil {
- log.Println(err)
- return "", errors.New("Couldn't generate random string")
- }
-
- return base64.URLEncoding.EncodeToString(buf)[:size], nil
- }
|