189
handler/auth/google/callback/callback.go
Normal file
189
handler/auth/google/callback/callback.go
Normal file
@ -0,0 +1,189 @@
|
|||||||
|
package googleOauthCallbackHandler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"github.com/fossyy/filekeeper/cache"
|
||||||
|
"github.com/fossyy/filekeeper/db"
|
||||||
|
googleOauthSetupHandler "github.com/fossyy/filekeeper/handler/auth/google/setup"
|
||||||
|
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") {
|
||||||
|
code := utils.GenerateRandomString(64)
|
||||||
|
googleOauthSetupHandler.SetupUser[code] = &googleOauthSetupHandler.UnregisteredUser{
|
||||||
|
Code: code,
|
||||||
|
Email: oauthUser.Email,
|
||||||
|
CreateTime: time.Now(),
|
||||||
|
}
|
||||||
|
http.Redirect(w, r, fmt.Sprintf("/auth/google/setup/%s", code), 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
|
||||||
|
}
|
20
handler/auth/google/google.go
Normal file
20
handler/auth/google/google.go
Normal 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&client_id=%s", token, utils.Getenv("GOOGLE_CALLBACK"), utils.Getenv("GOOGLE_CLIENT_ID")), http.StatusFound)
|
||||||
|
return
|
||||||
|
}
|
159
handler/auth/google/setup/setup.go
Normal file
159
handler/auth/google/setup/setup.go
Normal file
@ -0,0 +1,159 @@
|
|||||||
|
package googleOauthSetupHandler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"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/types/models"
|
||||||
|
"github.com/fossyy/filekeeper/utils"
|
||||||
|
authView "github.com/fossyy/filekeeper/view/auth"
|
||||||
|
signupView "github.com/fossyy/filekeeper/view/signup"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"net/http"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type UnregisteredUser struct {
|
||||||
|
Code string
|
||||||
|
Email string
|
||||||
|
CreateTime time.Time
|
||||||
|
mu sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
var log *logger.AggregatedLogger
|
||||||
|
var SetupUser map[string]*UnregisteredUser
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
log = logger.Logger()
|
||||||
|
SetupUser = make(map[string]*UnregisteredUser)
|
||||||
|
|
||||||
|
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 [GoogleSetup] [%s] initiated at %02d:%02d:%02d", cleanID, currentTime.Hour(), currentTime.Minute(), currentTime.Second()))
|
||||||
|
|
||||||
|
for _, data := range SetupUser {
|
||||||
|
data.mu.Lock()
|
||||||
|
if currentTime.Sub(data.CreateTime) > time.Minute*10 {
|
||||||
|
delete(SetupUser, data.Code)
|
||||||
|
cacheClean++
|
||||||
|
}
|
||||||
|
|
||||||
|
data.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info(fmt.Sprintf("Cache cleanup [GoogleSetup] [%s] completed: %d entries removed. Finished at %s", cleanID, cacheClean, time.Since(currentTime)))
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
func GET(w http.ResponseWriter, r *http.Request) {
|
||||||
|
code := r.PathValue("code")
|
||||||
|
if _, ok := SetupUser[code]; !ok {
|
||||||
|
http.Redirect(w, r, "/signup", http.StatusSeeOther)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
component := authView.GoogleSetup("Setup page", types.Message{
|
||||||
|
Code: 3,
|
||||||
|
Message: "",
|
||||||
|
})
|
||||||
|
err := component.Render(r.Context(), w)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
log.Error(err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func POST(w http.ResponseWriter, r *http.Request) {
|
||||||
|
code := r.PathValue("code")
|
||||||
|
unregisteredUser, ok := SetupUser[code]
|
||||||
|
if !ok {
|
||||||
|
http.Error(w, "Unauthorized Action", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err := r.ParseForm()
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
log.Error(err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
username := r.Form.Get("username")
|
||||||
|
password := r.Form.Get("password")
|
||||||
|
|
||||||
|
isValid := utils.ValidatePassword(password)
|
||||||
|
if !isValid {
|
||||||
|
component := authView.GoogleSetup("Setup page", types.Message{
|
||||||
|
Code: 0,
|
||||||
|
Message: "Password is invalid",
|
||||||
|
})
|
||||||
|
err := component.Render(r.Context(), w)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
log.Error(err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
hashedPassword, err := utils.HashPassword(password)
|
||||||
|
userID := uuid.New()
|
||||||
|
newUser := models.User{
|
||||||
|
UserID: userID,
|
||||||
|
Username: username,
|
||||||
|
Email: unregisteredUser.Email,
|
||||||
|
Password: hashedPassword,
|
||||||
|
}
|
||||||
|
|
||||||
|
err = db.DB.CreateUser(&newUser)
|
||||||
|
if err != nil {
|
||||||
|
component := signupView.Main("Sign up Page", types.Message{
|
||||||
|
Code: 0,
|
||||||
|
Message: "Email or Username has been registered",
|
||||||
|
})
|
||||||
|
err := component.Render(r.Context(), w)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
log.Error(err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
delete(SetupUser, code)
|
||||||
|
|
||||||
|
storeSession := session.GlobalSessionStore.Create()
|
||||||
|
storeSession.Values["user"] = types.User{
|
||||||
|
UserID: userID,
|
||||||
|
Email: unregisteredUser.Email,
|
||||||
|
Username: 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(unregisteredUser.Email, &sessionInfo)
|
||||||
|
|
||||||
|
http.Redirect(w, r, "/user", http.StatusSeeOther)
|
||||||
|
return
|
||||||
|
}
|
@ -67,7 +67,7 @@ func POST(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
userAgent := r.Header.Get("User-Agent")
|
userAgent := r.Header.Get("User-Agent")
|
||||||
browserInfo, osInfo := parseUserAgent(userAgent)
|
browserInfo, osInfo := ParseUserAgent(userAgent)
|
||||||
|
|
||||||
sessionInfo := session.SessionInfo{
|
sessionInfo := session.SessionInfo{
|
||||||
SessionID: storeSession.ID,
|
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)
|
browserInfo := make(map[string]string)
|
||||||
osInfo := make(map[string]string)
|
osInfo := make(map[string]string)
|
||||||
if strings.Contains(userAgent, "Firefox") {
|
if strings.Contains(userAgent, "Firefox") {
|
||||||
|
@ -1,8 +1,9 @@
|
|||||||
package routes
|
package routes
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
googleOauthHandler "github.com/fossyy/filekeeper/handler/auth/google"
|
||||||
|
googleOauthCallbackHandler "github.com/fossyy/filekeeper/handler/auth/google/callback"
|
||||||
|
googleOauthSetupHandler "github.com/fossyy/filekeeper/handler/auth/google/setup"
|
||||||
downloadHandler "github.com/fossyy/filekeeper/handler/download"
|
downloadHandler "github.com/fossyy/filekeeper/handler/download"
|
||||||
downloadFileHandler "github.com/fossyy/filekeeper/handler/download/file"
|
downloadFileHandler "github.com/fossyy/filekeeper/handler/download/file"
|
||||||
forgotPasswordHandler "github.com/fossyy/filekeeper/handler/forgotPassword"
|
forgotPasswordHandler "github.com/fossyy/filekeeper/handler/forgotPassword"
|
||||||
@ -17,6 +18,7 @@ import (
|
|||||||
"github.com/fossyy/filekeeper/handler/upload/initialisation"
|
"github.com/fossyy/filekeeper/handler/upload/initialisation"
|
||||||
userHandler "github.com/fossyy/filekeeper/handler/user"
|
userHandler "github.com/fossyy/filekeeper/handler/user"
|
||||||
"github.com/fossyy/filekeeper/middleware"
|
"github.com/fossyy/filekeeper/middleware"
|
||||||
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
func SetupRoutes() *http.ServeMux {
|
func SetupRoutes() *http.ServeMux {
|
||||||
@ -36,6 +38,38 @@ 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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
authRouter.HandleFunc("/google/setup/{code}", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.Method {
|
||||||
|
case http.MethodGet:
|
||||||
|
middleware.Guest(googleOauthSetupHandler.GET, w, r)
|
||||||
|
case http.MethodPost:
|
||||||
|
middleware.Guest(googleOauthSetupHandler.POST, w, r)
|
||||||
|
default:
|
||||||
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
handler.HandleFunc("/signin", func(w http.ResponseWriter, r *http.Request) {
|
handler.HandleFunc("/signin", func(w http.ResponseWriter, r *http.Request) {
|
||||||
switch r.Method {
|
switch r.Method {
|
||||||
case http.MethodGet:
|
case http.MethodGet:
|
||||||
|
@ -72,6 +72,7 @@ func (s *Session) Save(w http.ResponseWriter) {
|
|||||||
Name: utils.Getenv("SESSION_NAME"),
|
Name: utils.Getenv("SESSION_NAME"),
|
||||||
Value: s.ID,
|
Value: s.ID,
|
||||||
MaxAge: maxAge,
|
MaxAge: maxAge,
|
||||||
|
Path: "/",
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,8 +1,11 @@
|
|||||||
package utils
|
package utils
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
cryptoRand "crypto/rand"
|
||||||
|
"crypto/sha1"
|
||||||
|
"encoding/base64"
|
||||||
"fmt"
|
"fmt"
|
||||||
"math/rand"
|
mathRand "math/rand"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
@ -23,6 +26,10 @@ type Env struct {
|
|||||||
var env *Env
|
var env *Env
|
||||||
var log *logger.AggregatedLogger
|
var log *logger.AggregatedLogger
|
||||||
|
|
||||||
|
const (
|
||||||
|
csrfTokenLength = 32 // Length of the CSRF token in bytes
|
||||||
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
env = &Env{value: map[string]string{}}
|
env = &Env{value: map[string]string{}}
|
||||||
}
|
}
|
||||||
@ -124,7 +131,7 @@ func Getenv(key string) string {
|
|||||||
|
|
||||||
func GenerateRandomString(length int) string {
|
func GenerateRandomString(length int) string {
|
||||||
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
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
|
var result strings.Builder
|
||||||
for i := 0; i < length; i++ {
|
for i := 0; i < length; i++ {
|
||||||
randomIndex := seededRand.Intn(len(charset))
|
randomIndex := seededRand.Intn(len(charset))
|
||||||
@ -133,6 +140,21 @@ func GenerateRandomString(length int) string {
|
|||||||
return result.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 {
|
func SanitizeFilename(filename string) string {
|
||||||
invalidChars := []string{"\\", "/", ":", "*", "?", "\"", "<", ">", "|"}
|
invalidChars := []string{"\\", "/", ":", "*", "?", "\"", "<", ">", "|"}
|
||||||
|
|
||||||
|
90
view/auth/auth.templ
Normal file
90
view/auth/auth.templ
Normal file
@ -0,0 +1,90 @@
|
|||||||
|
package authView
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/fossyy/filekeeper/types"
|
||||||
|
"github.com/fossyy/filekeeper/view/layout"
|
||||||
|
)
|
||||||
|
|
||||||
|
templ form(err types.Message, title string) {
|
||||||
|
@layout.Base(title){
|
||||||
|
<div class="dark flex items-center min-h-screen p-4 sm:p-6 bg-gray-900">
|
||||||
|
<div class="mx-auto w-full max-w-md space-y-8">
|
||||||
|
<header class="text-center">
|
||||||
|
<div class="space-y-2">
|
||||||
|
<h1 class="text-3xl font-bold text-white">Sign Up</h1>
|
||||||
|
<p class="text-gray-500 dark:text-gray-400">Enter your email below to login to your account</p>
|
||||||
|
switch err.Code {
|
||||||
|
case 0:
|
||||||
|
<div class="p-4 mb-4 text-sm text-red-800 rounded-lg bg-red-50 dark:bg-gray-800 dark:text-red-400" role="alert">
|
||||||
|
<span class="font-medium">Danger alert!</span> {err.Message}
|
||||||
|
</div>
|
||||||
|
case 1:
|
||||||
|
<div class="p-4 mb-4 text-sm text-green-800 rounded-lg bg-green-50 dark:bg-gray-800 dark:text-green-400" role="alert">
|
||||||
|
<span class="font-medium">Success alert!</span> {err.Message}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<form class="space-y-4" method="post" action="">
|
||||||
|
<div class="space-y-2">
|
||||||
|
<label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 text-white" for="username">Username</label>
|
||||||
|
<input type="text" class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-gray-800 dark:text-white" id="username" name="username" required="" />
|
||||||
|
</div>
|
||||||
|
<div class="space-y-2">
|
||||||
|
<label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 text-white" for="password">Password</label>
|
||||||
|
<input type="password" class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-gray-800 dark:text-white" id="password" name="password" required />
|
||||||
|
</div>
|
||||||
|
<div class="space-y-2">
|
||||||
|
<label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 text-white" for="confirmPassword">Confirm Password</label>
|
||||||
|
<input type="password" class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-gray-800 dark:text-white" id="confirmPassword" required />
|
||||||
|
</div>
|
||||||
|
<div class="flex justify-start mt-3 ml-4 p-1">
|
||||||
|
<ul>
|
||||||
|
<li class="flex items-center py-1">
|
||||||
|
<div id="matchSvgContainer" class="rounded-full p-1 fill-current bg-red-200 text-green-700">
|
||||||
|
<svg id="matchSvgIcon" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||||
|
<path id="matchGoodPath" style="display: none;" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
|
||||||
|
<path id="matchBadPath" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<span id="matchStatusText" class="font-medium text-sm ml-3 text-red-700"> Passwords do not match</span>
|
||||||
|
</li>
|
||||||
|
<li class="flex items-center py-1">
|
||||||
|
<div id="lengthSvgContainer" class="rounded-full p-1 fill-current bg-red-200 text-green-700">
|
||||||
|
<svg id="lengthSvgIcon" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||||
|
<path id="lengthGoodPath" style="display: none;" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
|
||||||
|
<path id="lengthBadPath" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<span id="lengthStatusText" class="font-medium text-sm ml-3 text-red-700"> Password length must be at least 8 characters</span>
|
||||||
|
</li>
|
||||||
|
<li class="flex items-center py-1">
|
||||||
|
<div id="requirementsSvgContainer" class="rounded-full p-1 fill-current bg-red-200 text-green-700">
|
||||||
|
<svg id="requirementsSvgIcon" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||||
|
<path id="requirementsGoodPath" style="display: none;" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
|
||||||
|
<path id="requirementsBadPath" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<span id="requirementsStatusText" class="font-medium text-sm ml-3 text-red-700">The password must contain at least one symbol (!@#$%^&*), one uppercase letter, and three numbers</span>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
<button class="bg-slate-200 inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 bg-primary text-primary-foreground hover:bg-primary/90 h-10 px-4 py-2 w-full" type="submit" id="submit" name="submit" disabled>
|
||||||
|
Sign up
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
<div class="text-center text-sm text-white">
|
||||||
|
Already have an account?
|
||||||
|
<a class="underline" href="/signin" rel="ugc">
|
||||||
|
Sign in
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<script src="/public/validatePassword.js" />
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
templ GoogleSetup(title string, err types.Message) {
|
||||||
|
@form(err, title)
|
||||||
|
}
|
@ -39,6 +39,17 @@ templ content(err types.Message, title string) {
|
|||||||
Login
|
Login
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</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">
|
<div class="text-center text-sm text-white">
|
||||||
Don't have an account?
|
Don't have an account?
|
||||||
<a class="underline" href="/signup" rel="ugc">
|
<a class="underline" href="/signup" rel="ugc">
|
||||||
|
Reference in New Issue
Block a user