|
1 | 1 | package controllers
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "fmt" |
4 | 5 | "net/http"
|
| 6 | + |
| 7 | + "github.com/blastbeatsandcode/blastbeatsandcode-website/utils" |
5 | 8 | )
|
6 | 9 |
|
7 |
| -/* LoginHandler serves the login page */ |
8 |
| -func LoginHandler(w http.ResponseWriter, r *http.Request) { |
9 |
| - err := tpl.Get("login").ExecuteTemplate(w, "base-tpl", nil) |
10 |
| - checkErr(err) |
| 10 | +// /* LoginHandler serves the login page */ |
| 11 | +// func LoginHandler(w http.ResponseWriter, r *http.Request) { |
| 12 | +// err := tpl.Get("login").ExecuteTemplate(w, "base-tpl", nil) |
| 13 | +// checkErr(err) |
| 14 | +// } |
| 15 | + |
| 16 | +/* AuthGetHandler handles login GET requests */ |
| 17 | +func AuthGetHandler(w http.ResponseWriter, r *http.Request) { |
| 18 | + isAuth := utils.HandleAccess(r) |
| 19 | + |
| 20 | + // Check if we have a username |
| 21 | + // If we do, tell the user they are logged in |
| 22 | + if isAuth { |
| 23 | + redirURL := "/edit" |
| 24 | + http.Redirect(w, r, redirURL, http.StatusSeeOther) |
| 25 | + } else { |
| 26 | + err := tpl.Get("login").ExecuteTemplate(w, "base-tpl", nil) |
| 27 | + checkErr(err) |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +/* Takes information from login POST requests and logs user in or shows error */ |
| 32 | +func AuthPostHandler(w http.ResponseWriter, r *http.Request) { |
| 33 | + r.ParseForm() |
| 34 | + username := r.PostForm.Get("username") |
| 35 | + password := r.PostForm.Get("password") |
| 36 | + |
| 37 | + err := utils.CheckLogin(username, password) |
| 38 | + |
| 39 | + if err != nil { // If error is not nil, then the login does not match |
| 40 | + username = "" |
| 41 | + fmt.Println("THERE WAS AN ERROR LOGGING IN") |
| 42 | + } |
| 43 | + |
| 44 | + // Save the session |
| 45 | + store := utils.GetStore() |
| 46 | + session, _ := store.Get(r, "session") |
| 47 | + |
| 48 | + session.Values["username"] = username |
| 49 | + session.Save(r, w) |
| 50 | + |
| 51 | + // Check if we have a matching project ID |
| 52 | + // If we do, load edit page, otherwise prompt for login |
| 53 | + isAuth := utils.HandleAccess(r) |
| 54 | + |
| 55 | + // If user is authorized to edit and the request matches, load edit page |
| 56 | + if isAuth { |
| 57 | + redirURL := "/edit" |
| 58 | + http.Redirect(w, r, redirURL, http.StatusSeeOther) |
| 59 | + } else { // Otherwise load the login-failed template |
| 60 | + session.Values["username"] = "" |
| 61 | + session.Save(r, w) |
| 62 | + err := tpl.Get("login").ExecuteTemplate(w, "base-tpl", nil) |
| 63 | + checkErr(err) |
| 64 | + } |
11 | 65 | }
|
0 commit comments