2016-01-15 01:27:30 +00:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"net/http"
|
2016-01-19 19:31:22 +00:00
|
|
|
"time"
|
2016-01-15 01:27:30 +00:00
|
|
|
|
|
|
|
"github.com/khlieng/dispatch/storage"
|
|
|
|
)
|
|
|
|
|
2016-01-25 05:01:40 +00:00
|
|
|
const (
|
|
|
|
cookieName = "dispatch"
|
|
|
|
)
|
|
|
|
|
2016-01-15 01:27:30 +00:00
|
|
|
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)
|
2016-01-15 01:27:30 +00:00
|
|
|
} 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 {
|
2016-01-15 01:27:30 +00:00
|
|
|
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)
|
2016-01-15 01:27:30 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil
|
|
|
|
}
|
2018-04-26 19:32:21 +00:00
|
|
|
sessions.set(session)
|
|
|
|
go session.run()
|
2016-01-15 01:27:30 +00:00
|
|
|
|
|
|
|
http.SetCookie(w, &http.Cookie{
|
|
|
|
Name: cookieName,
|
2018-04-26 19:32:21 +00:00
|
|
|
Value: session.id,
|
2016-01-15 01:27:30 +00:00
|
|
|
Path: "/",
|
2016-01-19 19:31:22 +00:00
|
|
|
Expires: time.Now().AddDate(0, 1, 0),
|
2016-01-15 01:27:30 +00:00
|
|
|
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)
|
|
|
|
}
|