97 lines
2.4 KiB
Go
97 lines
2.4 KiB
Go
package site
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net/http"
|
|
"ruben/inventory2/internal/site/response"
|
|
"time"
|
|
)
|
|
|
|
// GET /login
|
|
func (s *Server) loginPage(r *http.Request) (response.Response, error) {
|
|
ctx := r.Context()
|
|
|
|
u, err := s.newLoginURL(ctx, "/")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return response.TemporaryRedirect(u), nil
|
|
}
|
|
|
|
func (s *Server) newLoginURL(ctx context.Context, targetURI string) (string, error) {
|
|
state, err := s.auth.NewState(ctx, targetURI)
|
|
if err != nil {
|
|
return "", fmt.Errorf("failed to generate random state: %w", err)
|
|
}
|
|
|
|
base64EncodedState := fmt.Sprintf("%x", state[:])
|
|
|
|
return s.auth.AuthCodeURL(base64EncodedState), nil
|
|
}
|
|
|
|
// POST /login
|
|
func (s *Server) login(r *http.Request) (response.Response, error) {
|
|
ctx := r.Context()
|
|
email := r.FormValue("email")
|
|
if email == "" {
|
|
return nil, response.BadRequest().Msg("no email provided")
|
|
}
|
|
|
|
acct, err := s.accts.GetAccountByEmail(ctx, email)
|
|
if err != nil {
|
|
return nil, response.Errorf("failed to create account: %w", err)
|
|
}
|
|
|
|
return response.SeeOther(fmt.Sprintf("/accounts/%d", acct.ID)), nil
|
|
}
|
|
|
|
// GET /login/callback
|
|
func (s *Server) loginCallback(r *http.Request) (response.Response, error) {
|
|
ctx := r.Context()
|
|
q := r.URL.Query()
|
|
|
|
// obtain token and profile
|
|
|
|
accessToken, targetURI, expiration, err := s.auth.Exchange(ctx, q.Get("state"), q.Get("code"))
|
|
if err != nil {
|
|
return nil, response.Unauthorized().
|
|
Msg(fmt.Sprintf("Failed to exchange an authorization code for a token")).
|
|
Wrap(err)
|
|
}
|
|
|
|
// set access_token cookie and redirect to a reasonable place
|
|
|
|
return response.TemporaryRedirect(targetURI).
|
|
Cookie(newAccessTokenCookie(accessToken, expiration)), nil
|
|
}
|
|
|
|
func newAccessTokenCookie(tkn string, expiration time.Time) http.Cookie {
|
|
return http.Cookie{
|
|
Name: "access_token",
|
|
Value: tkn,
|
|
Path: "/",
|
|
Expires: expiration,
|
|
MaxAge: 0, // using Expiration instead
|
|
Secure: true,
|
|
}
|
|
}
|
|
|
|
// GET /logout
|
|
func (s *Server) logoutPage(r *http.Request) (response.Response, error) {
|
|
host := r.Header.Get("X-Forwarded-Host")
|
|
if host == "" {
|
|
host = r.Host
|
|
}
|
|
|
|
if ck, err := r.Cookie("access_token"); err == nil && ck != nil {
|
|
if err := s.auth.DeleteOAuthTokens(r.Context(), ck.Value); err != nil {
|
|
fmt.Println("[ERROR] failed to delete auth token:", err)
|
|
}
|
|
}
|
|
|
|
return response.TemporaryRedirect(s.auth.GetLogoutURL(host).String()).
|
|
Cookie(getExpiredCookie("access_token")), nil
|
|
}
|