all repos — auth-boilerplate @ 11306ab298ac8d3dcc76c08302590f317dbc7b55

A simple Go web-app boilerplate.

src/app/functions.go (view raw)

 1package app
 2
 3import (
 4	"context"
 5	"errors"
 6	"fmt"
 7	"log"
 8	"net/http"
 9	"os"
10	"time"
11
12	"github.com/birabittoh/auth-boilerplate/src/email"
13)
14
15func login(w http.ResponseWriter, userID uint, remember bool) {
16	var duration time.Duration
17	if remember {
18		duration = durationWeek
19	} else {
20		duration = durationDay
21	}
22
23	cookie, err := g.GenerateCookie(duration)
24	if err != nil {
25		http.Error(w, "Could not generate session cookie.", http.StatusInternalServerError)
26	}
27
28	ks.Set(cookie.Value, userID, duration)
29	http.SetCookie(w, cookie)
30}
31
32func loadEmailConfig() *email.Client {
33	address := os.Getenv("APP_SMTP_EMAIL")
34	password := os.Getenv("APP_SMTP_PASSWORD")
35	host := os.Getenv("APP_SMTP_HOST")
36	port := os.Getenv("APP_SMTP_PORT")
37
38	if address == "" || password == "" || host == "" {
39		log.Println("Missing email configuration.")
40		return nil
41	}
42
43	if port == "" {
44		port = "587"
45	}
46
47	return email.NewClient(address, password, host, port)
48}
49
50func sendEmail(mail email.Email) error {
51	if m == nil {
52		return errors.New("email client is not initialized")
53	}
54	return m.Send(mail)
55}
56
57func sendResetEmail(address, token string) {
58	resetURL := fmt.Sprintf("%s/reset-password-confirm?token=%s", baseUrl, token)
59	err := sendEmail(email.Email{
60		To:      []string{address},
61		Subject: "Reset password",
62		Body:    fmt.Sprintf("Use this link to reset your password: %s", resetURL),
63	})
64	if err != nil {
65		log.Printf("Could not send reset email for %s. Link: %s", address, resetURL)
66	}
67}
68
69func readSessionCookie(r *http.Request) (userID *uint, err error) {
70	cookie, err := r.Cookie("session_token")
71	if err != nil {
72		return
73	}
74	return ks.Get(cookie.Value)
75}
76
77// Middleware to check if the user is logged in
78func loginRequired(next http.HandlerFunc) http.HandlerFunc {
79	return func(w http.ResponseWriter, r *http.Request) {
80		userID, err := readSessionCookie(r)
81		if err != nil {
82			http.Redirect(w, r, "/login", http.StatusFound)
83			return
84		}
85
86		ctx := context.WithValue(r.Context(), userContextKey, *userID)
87		next(w, r.WithContext(ctx))
88	}
89}
90
91func getLoggedUser(r *http.Request) (user User, ok bool) {
92	userID, ok := r.Context().Value(userContextKey).(uint)
93	db.Find(&user, userID)
94	return user, ok
95}