github.com/nizigama/simple-note@v0.0.0-20210501235539-2cc762e06fe8/services/middleware/authentication.go (about)

     1  package auth
     2  
     3  import (
     4  	"net/http"
     5  	"strconv"
     6  
     7  	"github.com/nizigama/simple-note/models"
     8  	"golang.org/x/crypto/bcrypt"
     9  )
    10  
    11  type Session struct {
    12  	ID     uint64
    13  	UserID int
    14  }
    15  
    16  var Sessions []Session
    17  
    18  func Authorize(f func(http.ResponseWriter, *http.Request)) http.Handler {
    19  
    20  	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
    21  		c, err := req.Cookie("sessionID")
    22  		if err != nil {
    23  			// no cookie with sessionID found
    24  			if req.URL.Path == "/login" || req.URL.Path == "/register" {
    25  				f(w, req)
    26  				return
    27  			}
    28  			w.Header().Set("Location", "/login")
    29  			w.WriteHeader(http.StatusSeeOther)
    30  			return
    31  		}
    32  		for _, v := range Sessions {
    33  			if c.Value == strconv.Itoa(int(v.ID)) {
    34  				_, err := models.ReadUser(uint64(v.UserID))
    35  				if err != nil {
    36  					// no user found
    37  					if req.URL.Path == "/login" || req.URL.Path == "/register" {
    38  						f(w, req)
    39  						return
    40  					}
    41  					w.Header().Set("Location", "/login")
    42  					w.WriteHeader(http.StatusSeeOther)
    43  					return
    44  				}
    45  				if req.URL.Path == "/login" || req.URL.Path == "/register" {
    46  					// login and register are not available for logged in user
    47  					w.Header().Set("Location", "/")
    48  					w.WriteHeader(http.StatusSeeOther)
    49  					return
    50  				}
    51  				// proceed with requested path handler
    52  				f(w, req)
    53  				return
    54  			}
    55  		}
    56  
    57  		// no sessionID found
    58  		if c.Value != "" {
    59  			c.MaxAge = -1
    60  			http.SetCookie(w, c)
    61  		}
    62  		w.Header().Set("Location", "/login")
    63  		w.WriteHeader(http.StatusSeeOther)
    64  	})
    65  }
    66  
    67  func CheckCredentials(storedPassword, givenPassword []byte) error {
    68  
    69  	if err := bcrypt.CompareHashAndPassword(storedPassword, givenPassword); err != nil {
    70  		return err
    71  	}
    72  	return nil
    73  }
    74  
    75  func CreateSession(sessionID uint64, userID int) {
    76  	newSession := Session{
    77  		ID:     sessionID,
    78  		UserID: userID,
    79  	}
    80  
    81  	Sessions = append(Sessions, newSession)
    82  }