Langelozzi / stream-buster

A streaming site for the O.G.'s
https://stream-buster.vercel.app
1 stars 0 forks source link

Create auth handling #1

Closed camfung closed 2 weeks ago

camfung commented 3 weeks ago

put the code in place to create a jwt token tried to make a test to create then verify the token but the tests were failing. not sure why. i'll need to look into it more tmr

tmr i also want to make the login route to create the user in the db

camfung commented 3 weeks ago

I'm using this post as reference

camfung commented 3 weeks ago

Verify token returns a Token object from the jwt package. it is has this definition:

type Token struct {
    Raw       string                 // The raw token.  Populated when you Parse a token
    Method    SigningMethod          // The signing method used or to be used
    Header    map[string]interface{} // The first segment of the token
    Claims    Claims                 // The second segment of the token
    Signature string                 // The third segment of the token.  Populated when you Parse a token
    Valid     bool                   // Is the token valid?  Populated when you Parse/Verify a token
}
camfung commented 3 weeks ago
// auth_controller.go 
    if validCredentials {
        tokenString, err := contr.service.CreateToken(username)
        if err != nil {
            c.String(http.StatusInternalServerError, "Error creating token")
            return
        }

        loggedInUser := username
        fmt.Printf("Token created: %s\n", tokenString)
        c.SetCookie("token", tokenString, 3600, "/", "localhost", false, true)
        c.Redirect(http.StatusSeeOther, "/")
    } else {
        c.String(http.StatusUnauthorized, "Invalid credentials")
    }

had a thought to make the redirect destination dynamic but for now this is fine

camfung commented 3 weeks ago

added an env variable DOMAIN because we need it to set the cookie

camfung commented 3 weeks ago

So far i think that the jwt creation is working. i need to add refresh tokens to the mix.

camfung commented 3 weeks ago

I'm only returning the jwt in a cookie I'm not sure how i'm going to handle refresh tokens

camfung commented 3 weeks ago
// auth_controller.go
        c.SetCookie("refreshToken", refreshTokenString, 60*60*24*5)
func (service AuthService) CreateRefreshToken(username string) (string, error) {
    claims := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
        "sub":  username,                                  // Subject (user identifier)
        "type": "refresh-token",                           // type
        "exp":  time.Now().Add(time.Hour * 5 * 24).Unix(), // Expiration time
        "iat":  time.Now().Unix(),                         // Issued at
    })
    tokenString, err := claims.SignedString(secretKey)
    if err != nil {
        return "", err
    }
    return tokenString, nil
}

I need to make sure to move the 5 days to another file

camfung commented 3 weeks ago

I added the middle ware to a test route. so if you set a cookie to be token with a valid access token it'll let you in. i think it should also use the refresh token but I havnt tested that yet

camfung commented 3 weeks ago

DB_CONNECTION_STRING= JWT_SECRET_TOKEN= REFRESH_TOKEN_EXPIRATION_TIME=604800 DOMAIN="http://localhost:8080"

this is what my .env looks like @Langelozzi

camfung commented 3 weeks ago

added test for the refresh token. it works you need to make sure to add a valid token and refresh token to the tests or they'll fail

camfung commented 3 weeks ago

need to add a dao call to the user to get the user information. I since the user name is a unique identifier I can fetch on that.

camfung commented 3 weeks ago

should make an index in the db for the username since i'm going to be fetching based on that

camfung commented 3 weeks ago

need to add a create user route. I think that needs a user dao

camfung commented 3 weeks ago
// auth_controller.go
func (contr *AuthController) CreateUser(c *gin.Context) {
    username := c.PostForm("Username")
    firstName := c.PostForm("FirstName")
    lastName := c.PostForm("LastName")
    email := c.PostForm("Email")
    password := c.PostForm("Password")

    // Create the user object
    newUser := models.User{
        Username:  username,
        FirstName: firstName,
        LastName:  lastName,
        Email:     email,
        Password:  password,
    }

    createdUser, err := contr.userService.CreateUser(&newUser)
    if err != nil {
        c.String(400, "Error Creating user")
    }

    c.JSON(201, createdUser)
}

need to add handling for creating and issueing a token here. i think i can just create token

camfung commented 3 weeks ago

remove username

camfung commented 3 weeks ago

change the jwt so that it encodes the user into it

camfung commented 3 weeks ago

removed the username from the user model

camfung commented 2 weeks ago

remove casing from the email

camfung commented 2 weeks ago

changed the hasing to the backend

camfung commented 2 weeks ago
// auth_controller.go
func (contr *AuthController) CreateUser(c *gin.Context) {
  username := c.PostForm("Username")
  firstName := c.PostForm("FirstName")
  lastName := c.PostForm("LastName")
  email := c.PostForm("Email")
  password := c.PostForm("Password")

  // Create the user object
  newUser := models.User{
      Username:  username,
      FirstName: firstName,
      LastName:  lastName,
      Email:     email,
      Password:  password,
  }

  createdUser, err := contr.userService.CreateUser(&newUser)
  if err != nil {
      c.String(400, "Error Creating user")
  }

  c.JSON(201, createdUser)
}

need to add handling for creating and issueing a token here. i think i can just create token

I think that the user needs to sign in after creating an account