diff --git a/main.go b/main.go index 7112cdb2d72a70138f18cd4d6782e6b4dcc753b6..d2332a398b04dbe5012c83c046dec024f2b13804 100644 --- a/main.go +++ b/main.go @@ -60,10 +60,28 @@ func createSession(session Session) error { // Get a handle to the sessions collection sessionsCollection := client.Database("authentication").Collection("sessions") + // delete all sessions for the user from the sessions collection + _, err = sessionsCollection.DeleteMany(context.Background(), bson.M{"username": session.Username}) + // Insert the session into the sessions collection _, err = sessionsCollection.InsertOne(context.Background(), session) return err } + +func deleteUserSessions(username string) error { + // Connect to the MongoDB database + clientOptions := options.Client().ApplyURI(URI) + client, err := mongo.Connect(context.Background(), clientOptions) + if err != nil { + return err + } + defer client.Disconnect(context.Background()) + + // Delete all sessions for the user from the sessions collection + _, err = sessionsCollection.DeleteMany(context.Background(), bson.M{"username": username}) + return err +} + func getSession(sessionID string) (Session, error) { // Connect to the MongoDB database clientOptions := options.Client().ApplyURI(URI) @@ -1116,43 +1134,6 @@ func successSignin(w http.ResponseWriter, r *http.Request) { return } - id := uuid.NewV4() - - // Create a new session object - session := Session{ - ID: id.String(), - Username: r.FormValue("username"), - CreationTime: time.Now(), - } - - // Connect to the MongoDB database - clientOptions := options.Client().ApplyURI(URI) - client, err := mongo.Connect(context.Background(), clientOptions) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - defer client.Disconnect(context.Background()) - - // Store the session in the database - err = createSession(session) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - - cookie := &http.Cookie{ - Name: "session_id", - Value: session.ID, - Expires: time.Now().Add(24 * time.Hour), - HttpOnly: true, - } - http.SetCookie(w, cookie) - - username := cookie.Value - fmt.Println("printing username from cookie value") - fmt.Println(username) - err = tmpl.Execute(w, data) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) @@ -1520,5 +1501,16 @@ func signInHandler(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), http.StatusInternalServerError) return } + + cookie := &http.Cookie{ + Name: "session_id", + Value: session.ID, + Expires: time.Now().Add(24 * time.Hour), + HttpOnly: true, + } + http.SetCookie(w, cookie) + fmt.Println("printing username from cookie value") + fmt.Println(username) + http.Redirect(w, r, "/profile", http.StatusTemporaryRedirect) } diff --git a/output b/output index a5727f6b8a05f166432183c4f5ee9ddbbc9e1298..f3c473079a7cc00b1abffe60eb83b686a1a907c6 100755 Binary files a/output and b/output differ