Once User Sign up, we store the user data inside cookie in the broswer and also keep a memory copy in the server.
If next time, user refresh the page, we want to tell that the user is already authed.
Create a endpoint, to retrive the user data:
App.route ('/api/user ') . Get (GetUser);
Router:
Import {Request, Response} from ' Express '; import {Sessionstore} from'./session-store '; exportfunctionGetUser (req:request, res:response) {//Get SessionID from CookiesConst SESSIONID = req.cookies[' sessionId ']; //get user According to the session ID from the session storageConst USER =Sessionstore.finduserbysessionid (sessionId); if(user) {//If there is user, send successful responseRes.status (200). JSON (user); } Else { //If there is no user, send empty responseRes.sendstatus (204); }}
Sessionstorage:
Import {Session} from './session '; import {User} from‘.. /src/app/model/user 'class Sessionstore {private sessions: {[key:string]: Session}= {}; CreateSession (sessionid:string, user:user) { This. Sessions[sessionid] =NewSession (sessionId, user); } finduserbysessionid (sessionid:string): User|undefined {const session= This. Sessions[sessionid]; Const Issessionvalid= Session &&Session.isvalid (); returnIssessionvalid?session.user:undefined; }}//We want only global singletonExport Const Sessionstore =NewSessionstore ();
On the client, once page loaded, we try to get user data first.
Import {injectable} from ' @angular/core '; import {HttpClient} from' @angular/common/http '; import {Observable} from' Rxjs/observable '; import {User} from‘.. /model/user '; import {behaviorsubject} from' Rxjs/behaviorsubject '; Import' Rxjs/add/operator/map '; Import' Rxjs/add/operator/sharereplay '; Import' Rxjs/add/operator/filter '; Import' Rxjs/add/operator/do '; export const Anonymous_user:user={id:undefined, email:‘‘}; @Injectable () export class Authservice {subject=NewBehaviorsubject<user>(undefined); //filter out undefined useruser$: observable<user> = This. Subject.asobservable (). filter (user =!! user); isloggedin$: Observable<Boolean> = This. user$.map (user =!!user.id); isloggedout$: Observable<Boolean> = This. isloggedin$.map (isLoggedIn =!isLoggedIn); Constructor (private http:httpclient) {This .http.get<user> ('/api/user ') //When there is valid session ID, emit the user$. Subscribe (user) = This. Subject.next (user?user:anonymous_user)); } signUp (Email:string, password:string) {return This.http.post<user> ('/api/signup ', {email, password}). Sharereplay (). Do(user) = This. Subject.next (user)); }}
[Angular & Web] Retrieve User data from Session