Implement Google OAuth2

This commit is contained in:
2024-04-30 15:16:33 +07:00
parent 0b8d4af794
commit da31733dcc
7 changed files with 274 additions and 6 deletions

View File

@ -0,0 +1,182 @@
package googleOauthCallbackHandler
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/fossyy/filekeeper/cache"
"github.com/fossyy/filekeeper/db"
signinHandler "github.com/fossyy/filekeeper/handler/signin"
"github.com/fossyy/filekeeper/logger"
"github.com/fossyy/filekeeper/session"
"github.com/fossyy/filekeeper/types"
"github.com/fossyy/filekeeper/utils"
"net/http"
"net/url"
"sync"
"time"
)
//type OauthToken struct {
// AccessToken string `json:"access_token"`
// ExpiresIn int `json:"expires_in"`
// RefreshToken string `json:"refresh_token"`
// Scope string `json:"scope"`
// TokenType string `json:"token_type"`
// IdToken string `json:"id_token"`
//}
//
//type OauthUser struct {
// Id string `json:"id"`
// Email string `json:"email"`
// VerifiedEmail bool `json:"verified_email"`
// Name string `json:"name"`
// GivenName string `json:"given_name"`
// Picture string `json:"picture"`
// Locale string `json:"locale"`
//}
type OauthToken struct {
AccessToken string `json:"access_token"`
}
type OauthUser struct {
Email string `json:"email"`
VerifiedEmail bool `json:"verified_email"`
}
type CsrfToken struct {
Token string
CreateTime time.Time
mu sync.Mutex
}
var log *logger.AggregatedLogger
var CsrfTokens map[string]*CsrfToken
func init() {
log = logger.Logger()
CsrfTokens = make(map[string]*CsrfToken)
ticker := time.NewTicker(time.Minute)
go func() {
for {
<-ticker.C
currentTime := time.Now()
cacheClean := 0
cleanID := utils.GenerateRandomString(10)
log.Info(fmt.Sprintf("Cache cleanup [csrf_token] [%s] initiated at %02d:%02d:%02d", cleanID, currentTime.Hour(), currentTime.Minute(), currentTime.Second()))
for _, data := range CsrfTokens {
data.mu.Lock()
if currentTime.Sub(data.CreateTime) > time.Minute-10 {
delete(CsrfTokens, data.Token)
cacheClean++
}
data.mu.Unlock()
}
log.Info(fmt.Sprintf("Cache cleanup [csrf_token] [%s] completed: %d entries removed. Finished at %s", cleanID, cacheClean, time.Since(currentTime)))
}
}()
}
func GET(w http.ResponseWriter, r *http.Request) {
if _, ok := CsrfTokens[r.URL.Query().Get("state")]; !ok {
http.Error(w, "csrf token mismatch", http.StatusInternalServerError)
return
}
delete(CsrfTokens, r.URL.Query().Get("state"))
formData := url.Values{
"grant_type": {"authorization_code"},
"code": {r.URL.Query().Get("code")},
"client_id": {utils.Getenv("GOOGLE_CLIENT_ID")},
"client_secret": {utils.Getenv("GOOGLE_CLIENT_SECRET")},
"redirect_uri": {utils.Getenv("GOOGLE_CALLBACK")},
}
resp, err := http.Post("https://oauth2.googleapis.com/token", "application/x-www-form-urlencoded", bytes.NewBufferString(formData.Encode()))
if err != nil {
log.Error("Error:", err)
http.Error(w, "Failed to get token", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
var oauthData OauthToken
if err := json.NewDecoder(resp.Body).Decode(&oauthData); err != nil {
log.Error("Error reading token response body:", err)
http.Error(w, "Failed to read token response body", http.StatusInternalServerError)
return
}
client := &http.Client{}
req, err := http.NewRequest("GET", "https://www.googleapis.com/oauth2/v1/userinfo?alt=json", nil)
req.Header.Set("Authorization", "Bearer "+oauthData.AccessToken)
if err != nil {
log.Error("Error creating user info request:", err)
http.Error(w, "Failed to create user info request", http.StatusInternalServerError)
return
}
userInfoResp, err := client.Do(req)
defer userInfoResp.Body.Close()
var oauthUser OauthUser
if err := json.NewDecoder(userInfoResp.Body).Decode(&oauthUser); err != nil {
log.Error("Error reading user info response body:", err)
http.Error(w, "Failed to read user info response body", http.StatusInternalServerError)
return
}
if !db.DB.IsUserRegistered(oauthUser.Email, "ll") {
http.Redirect(w, r, "/signup", http.StatusSeeOther)
return
}
user, err := cache.GetUser(oauthUser.Email)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Error(err.Error())
return
}
storeSession := session.GlobalSessionStore.Create()
storeSession.Values["user"] = types.User{
UserID: user.UserID,
Email: oauthUser.Email,
Username: user.Username,
Authenticated: true,
}
userAgent := r.Header.Get("User-Agent")
browserInfo, osInfo := signinHandler.ParseUserAgent(userAgent)
sessionInfo := session.SessionInfo{
SessionID: storeSession.ID,
Browser: browserInfo["browser"],
Version: browserInfo["version"],
OS: osInfo["os"],
OSVersion: osInfo["version"],
IP: utils.ClientIP(r),
Location: "Indonesia",
}
storeSession.Save(w)
session.AddSessionInfo(oauthUser.Email, &sessionInfo)
cookie, err := r.Cookie("redirect")
if errors.Is(err, http.ErrNoCookie) {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
http.SetCookie(w, &http.Cookie{
Name: "redirect",
MaxAge: -1,
})
http.Redirect(w, r, cookie.Value, http.StatusSeeOther)
return
}

View File

@ -0,0 +1,20 @@
package googleOauthHandler
import (
"fmt"
googleOauthCallbackHandler "github.com/fossyy/filekeeper/handler/auth/google/callback"
"github.com/fossyy/filekeeper/utils"
"net/http"
"time"
)
func GET(w http.ResponseWriter, r *http.Request) {
token, err := utils.GenerateCSRFToken()
googleOauthCallbackHandler.CsrfTokens[token] = &googleOauthCallbackHandler.CsrfToken{Token: token, CreateTime: time.Now()}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, fmt.Sprintf("https://accounts.google.com/o/oauth2/auth?scope=email profile&response_type=code&access_type=offline&state=%s&redirect_uri=%s/auth/google/callback&client_id=%s", token, "http://localhost:8000", "324904877864-vrbqof7nea1l89316d26sk0s76105hc4.apps.googleusercontent.com"), http.StatusFound)
return
}

View File

@ -67,7 +67,7 @@ func POST(w http.ResponseWriter, r *http.Request) {
}
userAgent := r.Header.Get("User-Agent")
browserInfo, osInfo := parseUserAgent(userAgent)
browserInfo, osInfo := ParseUserAgent(userAgent)
sessionInfo := session.SessionInfo{
SessionID: storeSession.ID,
@ -106,7 +106,7 @@ func POST(w http.ResponseWriter, r *http.Request) {
}
}
func parseUserAgent(userAgent string) (map[string]string, map[string]string) {
func ParseUserAgent(userAgent string) (map[string]string, map[string]string) {
browserInfo := make(map[string]string)
osInfo := make(map[string]string)
if strings.Contains(userAgent, "Firefox") {

View File

@ -1,8 +1,8 @@
package routes
import (
"net/http"
googleOauthHandler "github.com/fossyy/filekeeper/handler/auth/google"
googleOauthCallbackHandler "github.com/fossyy/filekeeper/handler/auth/google/callback"
downloadHandler "github.com/fossyy/filekeeper/handler/download"
downloadFileHandler "github.com/fossyy/filekeeper/handler/download/file"
forgotPasswordHandler "github.com/fossyy/filekeeper/handler/forgotPassword"
@ -17,6 +17,7 @@ import (
"github.com/fossyy/filekeeper/handler/upload/initialisation"
userHandler "github.com/fossyy/filekeeper/handler/user"
"github.com/fossyy/filekeeper/middleware"
"net/http"
)
func SetupRoutes() *http.ServeMux {
@ -36,6 +37,37 @@ func SetupRoutes() *http.ServeMux {
}
})
authRouter := http.NewServeMux()
handler.Handle("/auth/", http.StripPrefix("/auth", authRouter))
authRouter.HandleFunc("/google", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
middleware.Guest(googleOauthHandler.GET, w, r)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
})
authRouter.HandleFunc("/google/callback", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
middleware.Guest(googleOauthCallbackHandler.GET, w, r)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
})
//TODO make a setup route for unregistered google oauth user
//authRouter.HandleFunc("/google/setup", func(w http.ResponseWriter, r *http.Request) {
// switch r.Method {
// case http.MethodGet:
// middleware.Guest(googleOauthSetupHandler.GET, w, r)
// default:
// http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
// }
//})
handler.HandleFunc("/signin", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:

View File

@ -72,6 +72,7 @@ func (s *Session) Save(w http.ResponseWriter) {
Name: utils.Getenv("SESSION_NAME"),
Value: s.ID,
MaxAge: maxAge,
Path: "/",
})
}

View File

@ -1,8 +1,11 @@
package utils
import (
cryptoRand "crypto/rand"
"crypto/sha1"
"encoding/base64"
"fmt"
"math/rand"
mathRand "math/rand"
"net/http"
"os"
"strings"
@ -23,6 +26,10 @@ type Env struct {
var env *Env
var log *logger.AggregatedLogger
const (
csrfTokenLength = 32 // Length of the CSRF token in bytes
)
func init() {
env = &Env{value: map[string]string{}}
}
@ -124,7 +131,7 @@ func Getenv(key string) string {
func GenerateRandomString(length int) string {
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
seededRand := rand.New(rand.NewSource(time.Now().UnixNano() + int64(rand.Intn(9999))))
seededRand := mathRand.New(mathRand.NewSource(time.Now().UnixNano() + int64(mathRand.Intn(9999))))
var result strings.Builder
for i := 0; i < length; i++ {
randomIndex := seededRand.Intn(len(charset))
@ -133,6 +140,21 @@ func GenerateRandomString(length int) string {
return result.String()
}
func GenerateCSRFToken() (string, error) {
tokenBytes := make([]byte, 32)
_, err := cryptoRand.Read(tokenBytes)
if err != nil {
return "", err
}
hash := sha1.New()
hash.Write(tokenBytes)
hashedToken := hash.Sum(nil)
csrfToken := base64.URLEncoding.EncodeToString(hashedToken)
return csrfToken, nil
}
func SanitizeFilename(filename string) string {
invalidChars := []string{"\\", "/", ":", "*", "?", "\"", "<", ">", "|"}

View File

@ -39,6 +39,17 @@ templ content(err types.Message, title string) {
Login
</button>
</form>
<div
class="my-4 flex items-center before:mt-0.5 before:flex-1 before:border-t before:border-neutral-300 after:mt-0.5 after:flex-1 after:border-t after:border-neutral-300">
<p
class="mx-4 mb-0 text-white text-center font-semibold">
OR
</p>
</div>
<a href="/auth/google" class="inline-flex items-center justify-center p-5 text-base font-medium text-gray-500 rounded-lg bg-gray-50 hover:text-gray-900 hover:bg-gray-100 h-10 px-4 py-2 w-full">
<svg class="h-6 w-6 mr-2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="800px" height="800px" viewBox="-0.5 0 48 48" version="1.1"> <title>Google-color</title> <desc>Created with Sketch.</desc> <defs> </defs> <g id="Icons" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <g id="Color-" transform="translate(-401.000000, -860.000000)"> <g id="Google" transform="translate(401.000000, 860.000000)"> <path d="M9.82727273,24 C9.82727273,22.4757333 10.0804318,21.0144 10.5322727,19.6437333 L2.62345455,13.6042667 C1.08206818,16.7338667 0.213636364,20.2602667 0.213636364,24 C0.213636364,27.7365333 1.081,31.2608 2.62025,34.3882667 L10.5247955,28.3370667 C10.0772273,26.9728 9.82727273,25.5168 9.82727273,24" id="Fill-1" fill="#FBBC05"> </path> <path d="M23.7136364,10.1333333 C27.025,10.1333333 30.0159091,11.3066667 32.3659091,13.2266667 L39.2022727,6.4 C35.0363636,2.77333333 29.6954545,0.533333333 23.7136364,0.533333333 C14.4268636,0.533333333 6.44540909,5.84426667 2.62345455,13.6042667 L10.5322727,19.6437333 C12.3545909,14.112 17.5491591,10.1333333 23.7136364,10.1333333" id="Fill-2" fill="#EB4335"> </path> <path d="M23.7136364,37.8666667 C17.5491591,37.8666667 12.3545909,33.888 10.5322727,28.3562667 L2.62345455,34.3946667 C6.44540909,42.1557333 14.4268636,47.4666667 23.7136364,47.4666667 C29.4455,47.4666667 34.9177955,45.4314667 39.0249545,41.6181333 L31.5177727,35.8144 C29.3995682,37.1488 26.7323182,37.8666667 23.7136364,37.8666667" id="Fill-3" fill="#34A853"> </path> <path d="M46.1454545,24 C46.1454545,22.6133333 45.9318182,21.12 45.6113636,19.7333333 L23.7136364,19.7333333 L23.7136364,28.8 L36.3181818,28.8 C35.6879545,31.8912 33.9724545,34.2677333 31.5177727,35.8144 L39.0249545,41.6181333 C43.3393409,37.6138667 46.1454545,31.6490667 46.1454545,24" id="Fill-4" fill="#4285F4"> </path> </g> </g> </g> </svg>
<span>Continue with Google</span>
</a>
<div class="text-center text-sm text-white">
Don't have an account?
<a class="underline" href="/signup" rel="ugc">