This commit is contained in:
yunginnanet 2020-01-11 16:34:02 -08:00 зафіксовано GitHub
джерело 309c8facd6
коміт 2dda055d6a
Не вдалося знайти GPG ключ що відповідає даному підпису
Ідентифікатор GPG ключа: 4AEE18F83AFDEB23

70
main.go

@ -11,6 +11,7 @@ import (
_ "github.com/lib/pq"
"github.com/lukesampson/figlet/figletlib"
"github.com/matcornic/hermes/v2"
"github.com/satori/go.uuid"
"golang.org/x/crypto/bcrypt"
"html/template"
"io/ioutil"
@ -69,6 +70,11 @@ func HTTPServ() {
r.HandleFunc("/login", LoginForm)
r.HandleFunc("/EmailTest", EmailTest)
//without rate limiting
//r.HandleFunc("/login/submit", Login)
//r.HandleFunc("/register/submit", Register)
//with rate limiting
r.Handle("/login/submit", tollbooth.LimitFuncHandler(tollbooth.NewLimiter(1, nil), Login)).Methods("POST")
r.Handle("/register/submit", tollbooth.LimitFuncHandler(tollbooth.NewLimiter(1, nil), Register)).Methods("POST")
@ -143,9 +149,33 @@ func EmailTest(w http.ResponseWriter, r *http.Request) {
}
func IndexShow(w http.ResponseWriter, r *http.Request) {
ip := strings.Split(r.RemoteAddr, ":")[0]
fmt.Println(ip)
fmt.Fprintf(w, ip)
c, err := r.Cookie("session_token")
if err != nil {
if err == http.ErrNoCookie {
// If the cookie is not set, return an unauthorized status
w.WriteHeader(http.StatusUnauthorized)
return
}
// For any other type of error, return a bad request status
w.WriteHeader(http.StatusBadRequest)
return
}
sessionToken := c.Value
// We then get the name of the user from our cache, where we set the session token
response, err := cache.Do("GET", sessionToken)
if err != nil {
// If there is an error fetching from cache, return an internal server error status
w.WriteHeader(http.StatusInternalServerError)
return
}
if response == nil {
// If the session token is not present in cache, redirect to login screen
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
// Finally, return the welcome message to the user
w.Write([]byte(fmt.Sprintf("Welcome %s!", response)))
}
func LoginForm(w http.ResponseWriter, r *http.Request) {
@ -195,15 +225,6 @@ func Register(w http.ResponseWriter, r *http.Request) {
return
}
//Validates email addresses and makes sure they are under 254 characters
err0 := checkmail.ValidateFormat(EmailInput)
err1 := checkmail.ValidateHost(EmailInput)
if err0 != nil || err1 != nil {
fmt.Println("ERROR: that is not a valid email address!")
fmt.Println(w, "ERROR: that is not a valid email address!")
return
}
//Usernames must only be letters, numbers, dashes, and underscores
var rxUsername = regexp.MustCompile("([\\w\\-]+)")
//Usernames must be under 16 characters
@ -226,6 +247,15 @@ func Register(w http.ResponseWriter, r *http.Request) {
return
}
//Validates email addresses
err = checkmail.ValidateFormat(EmailInput)
if err != nil {
fmt.Println("ERROR: that is not a valid email address!")
fmt.Fprintf(w, "ERROR: that is not a valid email address!")
//return
panic(err)
}
fmt.Println("Passed checks, hashing password with bcrypt...")
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(PasswordInput), 16)
@ -272,6 +302,22 @@ func Login(w http.ResponseWriter, r *http.Request) {
// If we reach this point, that means the users password was correct, and that they are authorized
// The default 200 status is sent
fmt.Println("Authentication successful, setting session...")
//sets a 2 hour long session and cookie
sessionToken := uuid.NewV4().String()
_, err = cache.Do("SETEX", sessionToken, "7200", UsernameInput)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Println("Session management failed!")
http.SetCookie(w, &http.Cookie{
Name: "session_token",
Value: sessionToken,
Expires: time.Now().Add(7200 * time.Second),
})
return
}
fmt.Println("Login successful!")
fmt.Fprintf(w, "Login successful!")
}