dispatch/server/auth.go

64 lines
1.2 KiB
Go
Raw Normal View History

package server
import (
"log"
"net/http"
2016-01-19 19:31:22 +00:00
"time"
"github.com/khlieng/dispatch/storage"
)
const (
cookieName = "dispatch"
)
func handleAuth(w http.ResponseWriter, r *http.Request) *Session {
var session *Session
cookie, err := r.Cookie(cookieName)
if err != nil {
authLog(r, "No cookie set")
session = newUser(w, r)
} else {
2018-04-26 19:32:21 +00:00
session = sessions.get(cookie.Value)
if session != nil {
log.Println(r.RemoteAddr, "[Auth] GET", r.URL.Path, "| Valid token | User ID:", session.user.ID)
} else {
session = newUser(w, r)
}
}
return session
}
func newUser(w http.ResponseWriter, r *http.Request) *Session {
2016-01-17 20:15:29 +00:00
user, err := storage.NewUser()
if err != nil {
return nil
}
log.Println(r.RemoteAddr, "[Auth] Create session | User ID:", user.ID)
2018-04-26 19:32:21 +00:00
session, err := NewSession(user)
if err != nil {
return nil
}
2018-04-26 19:32:21 +00:00
sessions.set(session)
go session.run()
http.SetCookie(w, &http.Cookie{
Name: cookieName,
2018-04-26 19:32:21 +00:00
Value: session.id,
Path: "/",
2016-01-19 19:31:22 +00:00
Expires: time.Now().AddDate(0, 1, 0),
HttpOnly: true,
Secure: r.TLS != nil,
})
return session
}
func authLog(r *http.Request, s string) {
log.Println(r.RemoteAddr, "[Auth] GET", r.URL.Path, "|", s)
}