Improve logout

This commit is contained in:
Daniel Ponte 2024-11-22 17:05:29 -05:00
parent 55fdeaf086
commit dc8272b15f
5 changed files with 57 additions and 21 deletions

View file

@ -1,5 +1,5 @@
import { Router, CanActivateFn } from '@angular/router';
import { AuthService } from './login/auth.service'
import { AuthService } from './login/auth.service';
import { inject } from '@angular/core';
export const AuthGuard: CanActivateFn = (route, state) => {
@ -7,8 +7,7 @@ export const AuthGuard: CanActivateFn = (route, state) => {
const authSvc: AuthService = inject(AuthService);
if (sessionStorage.getItem('jwt') == null) {
let success = false;
authSvc.refresh()
.subscribe((event) => {
authSvc.refresh().subscribe((event) => {
if (event?.status == 200) {
success = true;
}
@ -16,7 +15,6 @@ export const AuthGuard: CanActivateFn = (route, state) => {
router.navigate(['/login']);
return success;
} else {
return true;
}
};

View file

@ -41,8 +41,23 @@ export class AuthService {
);
}
logout() {
this.http
.get('/api/logout', { withCredentials: true, observe: 'response' })
.subscribe((event) => {
if (event.status == 200) {
this.loggedIn = false;
}
});
sessionStorage.removeItem('jwt');
this.loggedIn = false;
this._router.navigateByUrl('/login');
}
refresh(): Observable<HttpResponse<Jwt>> {
return this.http.get<Jwt>('/api/refresh', { withCredentials: true, observe: 'response' }).pipe(
return this.http
.get<Jwt>('/api/refresh', { withCredentials: true, observe: 'response' })
.pipe(
tap((event) => {
if (event.status == 200) {
sessionStorage.setItem('jwt', event.body?.jwt.toString() ?? '');
@ -55,10 +70,4 @@ export class AuthService {
getToken(): string | null {
return sessionStorage.getItem('jwt');
}
logout() {
sessionStorage.removeItem('jwt');
this.loggedIn = false;
this._router.navigateByUrl('/login');
}
}

View file

@ -5,5 +5,6 @@ import (
)
const Prefix = "admin/dist/admin/browser"
//go:embed admin/dist/admin/browser
var Client embed.FS

View file

@ -77,6 +77,7 @@ func (a *Auth) PublicRoutes(r chi.Router) {
func (a *Auth) PrivateRoutes(r chi.Router) {
r.Get("/api/refresh", a.routeRefresh)
r.Get("/api/logout", a.routeLogout)
}
//go:embed login.html

View file

@ -237,3 +237,30 @@ func (a *Auth) routeAuth(w http.ResponseWriter, r *http.Request) {
render.JSON(w, r, &jr)
}
func (a *Auth) routeLogout(w http.ResponseWriter, r *http.Request) {
cookie := &http.Cookie{
Name: "jwt",
Value: "",
HttpOnly: true,
Secure: true,
Expires: time.Time{},
}
if a.allowInsecureCookie(r) {
cookie.Secure = false
cookie.SameSite = http.SameSiteLaxMode
} else {
cookie.Domain = a.cfg.Domain
}
http.SetCookie(w, cookie)
jr := struct {
Message string `json:"message"`
}{
Message: "logged out",
}
render.JSON(w, r, &jr)
}