github.com/mssola/todo@v0.0.0-20181029153210-d25348dc3f48/app/sessions.go (about)

     1  // Copyright (C) 2014-2017 Miquel Sabaté Solà <mikisabate@gmail.com>
     2  //
     3  // This Source Code Form is subject to the terms of the Mozilla Public
     4  // License, v. 2.0. If a copy of the MPL was not distributed with this
     5  // file, You can obtain one at http://mozilla.org/MPL/2.0/.
     6  
     7  package app
     8  
     9  import (
    10  	"encoding/json"
    11  	"fmt"
    12  	"net/http"
    13  
    14  	"github.com/mssola/todo/lib"
    15  )
    16  
    17  // Returns the name and the password parameters as given by the request. This
    18  // method abstracts away the origin of these values.
    19  func getNamePassword(req *http.Request) (string, string) {
    20  	if lib.JSONEncoding(req) {
    21  		if req.Body == nil {
    22  			return "", ""
    23  		}
    24  
    25  		decoder := json.NewDecoder(req.Body)
    26  
    27  		var t struct{ Name, Password string }
    28  		err := decoder.Decode(&t)
    29  		if err != nil {
    30  			return "", ""
    31  		}
    32  		return t.Name, t.Password
    33  	}
    34  	return req.FormValue("name"), req.FormValue("password")
    35  }
    36  
    37  // Login a user. It expects the "name" and "password" form values. Regardless
    38  // if it was successful or not, it will redirect the user to the root path.
    39  func Login(res http.ResponseWriter, req *http.Request) {
    40  	// Check if the user exists and that the password is spot on.
    41  	n, password := getNamePassword(req)
    42  	id, err := matchPassword(n, password)
    43  	if lib.CheckError(res, req, err) {
    44  		return
    45  	}
    46  
    47  	// It's ok to login this user.
    48  	if lib.JSONEncoding(req) {
    49  		b, _ := json.Marshal(User{ID: id})
    50  		fmt.Fprint(res, string(b))
    51  	} else {
    52  		lib.SetCookie(res, req, "userId", id)
    53  		http.Redirect(res, req, "/", http.StatusFound)
    54  	}
    55  }
    56  
    57  // Logout the current user.
    58  func Logout(res http.ResponseWriter, req *http.Request) {
    59  	lib.DeleteCookie(res, req, "userId")
    60  	lib.DeleteCookie(res, req, "topic")
    61  	http.Redirect(res, req, "/", http.StatusFound)
    62  }