2016-01-15 01:27:30 +00:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
|
2018-05-31 21:24:59 +00:00
|
|
|
"github.com/khlieng/dispatch/pkg/session"
|
2016-01-15 01:27:30 +00:00
|
|
|
"github.com/khlieng/dispatch/storage"
|
|
|
|
)
|
|
|
|
|
2018-11-08 07:39:47 +00:00
|
|
|
func (d *Dispatch) handleAuth(w http.ResponseWriter, r *http.Request, createUser, refresh bool) *State {
|
2018-05-31 21:24:59 +00:00
|
|
|
var state *State
|
2016-01-15 01:27:30 +00:00
|
|
|
|
2018-05-31 21:24:59 +00:00
|
|
|
cookie, err := r.Cookie(session.CookieName)
|
2016-01-15 01:27:30 +00:00
|
|
|
if err != nil {
|
2018-05-22 01:56:48 +00:00
|
|
|
if createUser {
|
2018-05-31 21:24:59 +00:00
|
|
|
state, err = d.newUser(w, r)
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
}
|
2018-05-22 01:56:48 +00:00
|
|
|
}
|
2016-01-15 01:27:30 +00:00
|
|
|
} else {
|
2018-05-31 21:24:59 +00:00
|
|
|
session := d.states.getSession(cookie.Value)
|
2018-04-26 19:32:21 +00:00
|
|
|
if session != nil {
|
2018-05-31 21:24:59 +00:00
|
|
|
key := session.Key()
|
|
|
|
|
2018-11-08 07:39:47 +00:00
|
|
|
if !session.Expired() {
|
2018-05-31 21:24:59 +00:00
|
|
|
state = d.states.get(session.UserID)
|
2018-11-08 07:39:47 +00:00
|
|
|
|
|
|
|
if refresh {
|
|
|
|
newKey, err := session.Refresh()
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if newKey != "" {
|
|
|
|
d.states.setSession(session)
|
|
|
|
d.states.deleteSession(key)
|
|
|
|
session.SetCookie(w, r)
|
|
|
|
}
|
2018-05-31 21:24:59 +00:00
|
|
|
}
|
2018-06-01 03:40:12 +00:00
|
|
|
} else {
|
|
|
|
d.states.deleteSession(key)
|
2018-05-31 21:24:59 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if state != nil {
|
|
|
|
log.Println(r.RemoteAddr, "[Auth] GET", r.URL.Path, "| Valid token | User ID:", state.user.ID)
|
2018-05-22 01:56:48 +00:00
|
|
|
} else if createUser {
|
2018-05-31 21:24:59 +00:00
|
|
|
state, err = d.newUser(w, r)
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
}
|
2016-01-15 01:27:30 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-05-31 21:24:59 +00:00
|
|
|
return state
|
2016-01-15 01:27:30 +00:00
|
|
|
}
|
|
|
|
|
2018-05-31 21:24:59 +00:00
|
|
|
func (d *Dispatch) newUser(w http.ResponseWriter, r *http.Request) (*State, error) {
|
|
|
|
user, err := storage.NewUser(d.Store)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Println(r.RemoteAddr, "[Auth] New anonymous user | ID:", user.ID)
|
2016-01-15 01:27:30 +00:00
|
|
|
|
2018-05-31 21:24:59 +00:00
|
|
|
session, err := session.New(user.ID)
|
2016-01-15 01:27:30 +00:00
|
|
|
if err != nil {
|
2018-05-31 21:24:59 +00:00
|
|
|
return nil, err
|
2016-01-15 01:27:30 +00:00
|
|
|
}
|
2018-05-31 21:24:59 +00:00
|
|
|
d.states.setSession(session)
|
|
|
|
|
|
|
|
state := NewState(user, d)
|
|
|
|
d.states.set(state)
|
|
|
|
go state.run()
|
|
|
|
|
|
|
|
session.SetCookie(w, r)
|
|
|
|
|
|
|
|
return state, nil
|
|
|
|
}
|