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"
|
|
|
|
)
|
|
|
|
|
2018-05-22 01:56:48 +00:00
|
|
|
func handleAuth(w http.ResponseWriter, r *http.Request, createUser bool) *Session {
|
2016-01-15 01:27:30 +00:00
|
|
|
var session *Session
|
|
|
|
|
|
|
|
cookie, err := r.Cookie(cookieName)
|
|
|
|
if err != nil {
|
2018-05-22 01:56:48 +00:00
|
|
|
if createUser {
|
|
|
|
session = newUser(w, r)
|
|
|
|
}
|
2016-01-15 01:27:30 +00:00
|
|
|
} 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)
|
2018-05-22 01:56:48 +00:00
|
|
|
} else if createUser {
|
2016-01-15 01:27:30 +00:00
|
|
|
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
|
|
|
|
}
|