Skip to content

Commit

Permalink
Migrate Session to Angular
Browse files Browse the repository at this point in the history
  • Loading branch information
sapanparikh18 committed Jan 19, 2024
1 parent 92a6ce0 commit 39dd8b2
Show file tree
Hide file tree
Showing 4 changed files with 235 additions and 148 deletions.
3 changes: 2 additions & 1 deletion app-new/src/app/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { AuthService } from './common/Session';
import { ReviewService } from './common/ReviewFactory';
import { OrderHistoryService } from './common/OrderHistoryFactory';
import { NgModule } from '@angular/core';
Expand All @@ -10,7 +11,7 @@ import { UpgradeModule } from '@angular/upgrade/static';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, AppRoutingModule, UpgradeModule],
providers: [ReviewService, OrderHistoryService, ],
providers: [AuthService, ReviewService, OrderHistoryService, ],
bootstrap: [AppComponent],
})
export class AppModule {}
91 changes: 91 additions & 0 deletions app-new/src/app/common/Session.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
// Import statements
import { Injectable } from '@angular/core';
import { downgradeInjectable } from '@angular/upgrade/static';
import * as angular from 'angular';

// Angular Service Definition
@Injectable({
providedIn: 'root',
})
export class AuthService {
constructor(private http: HttpClient, private session: SessionService, private router: Router, private eventService: EventService) {}

// Uses the session service to see if an authenticated user is currently registered.
isAuthenticated(): boolean {
return !!this.session.user;
}

getLoggedInUser(fromServer?: boolean): Promise<User | null> {
// If an authenticated session exists, we return the user attached to that session with a promise.
// This ensures that we can always interface with this method asynchronously.
// Optionally, if true is given as the fromServer parameter, then this cached value will not be used.
if (this.isAuthenticated() && !fromServer) {
return Promise.resolve(this.session.user);
}

// Make request GET /session.
// If it returns a user, call onSuccessfulLogin with the response.
// If it returns a 401 response, we catch it and instead resolve to null.
const URL = '/session';
const response = this.http
.get(URL)
.toPromise()
.then((res) => this.onSuccessfulLogin(res))
.catch(() => null);

return response;
}

signup(credentials: Credentials): Promise<User> {
const URL = '/signup';
const response = this.http
.post(URL, credentials)
.toPromise()
.then((res) => this.onSuccessfulLogin(res))
.catch(() => {
console.log('I CAUGHT THE POST REQUEST ERROR');
return Promise.reject({ message: 'Invalid signup credentials.' });
});

return response;
}

login(credentials: Credentials): Promise<User> {
const URL = '/login';
const response = this.http
.post(URL, credentials)
.toPromise()
.then((res) => this.onSuccessfulLogin(res))
.catch(() => {
console.log('THIS MESSAGE IS FROM AUTHSERVICE');
return Promise.reject({ message: 'Invalid login credentials.' });
});

return response;
}

logout(): Promise<void> {
const URL = '/logout';
const response = this.http
.get(URL)
.toPromise()
.then(() => {
this.session.destroy();
this.eventService.broadcast(AUTH_EVENTS.logoutSuccess);
});

return response;
}

private onSuccessfulLogin(response: any): User {
const data = response.data;
this.session.create(data.id, data.user);
this.eventService.broadcast(AUTH_EVENTS.loginSuccess);
return data.user;
}
}

// Downgrade Component for AngularJS Compatibility
angular
.module('fsaPreBuilt')
.service('AuthService', downgradeInjectable(AuthService));
147 changes: 0 additions & 147 deletions browser/js/fsa/fsa-pre-built.js

This file was deleted.

142 changes: 142 additions & 0 deletions src/app/Session.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
describe("fsaPreBuilt", function () {
beforeEach(module("FullstackGeneratedApp"));
beforeEach(module("$$UpgradeModule"));

var $controller, $rootScope, $scope, $httpBackend, AuthService, Session, AUTH_EVENTS;

beforeEach(inject(function (_$controller_, _$rootScope_, _$httpBackend_, _AuthService_, _Session_, _AUTH_EVENTS_) {
$controller = _$controller_;
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
$httpBackend = _$httpBackend_;
AuthService = _AuthService_;
Session = _Session_;
AUTH_EVENTS = _AUTH_EVENTS_;
}));

describe("AuthService", function () {
describe("isAuthenticated", function () {
it("should return true if user is authenticated", function () {
Session.user = { id: 1, name: "John Doe" };
var result = AuthService.isAuthenticated();
expect(result).toBe(true);
});

it("should return false if user is not authenticated", function () {
Session.user = null;
var result = AuthService.isAuthenticated();
expect(result).toBe(false);
});
});

describe("getLoggedInUser", function () {
it("should return the user attached to the session if user is authenticated and fromServer is not true", function () {
Session.user = { id: 1, name: "John Doe" };
var result;
AuthService.getLoggedInUser().then(function (user) {
result = user;
});
$rootScope.$digest();
expect(result).toEqual(Session.user);
});

it("should make a GET request to /session and call onSuccessfulLogin if user is not authenticated or fromServer is true", function () {
Session.user = null;
$httpBackend.expectGET("/session").respond(200, { id: 1, name: "John Doe" });
var result;
AuthService.getLoggedInUser().then(function (user) {
result = user;
});
$httpBackend.flush();
expect(result).toEqual({ id: 1, name: "John Doe" });
});

it("should catch a 401 response and resolve to null if user is not authenticated", function () {
Session.user = null;
$httpBackend.expectGET("/session").respond(401);
var result;
AuthService.getLoggedInUser().then(function (user) {
result = user;
});
$httpBackend.flush();
expect(result).toBeNull();
});
});

describe("signup", function () {
it("should make a POST request to /signup with the provided credentials and call onSuccessfulLogin if successful", function () {
var credentials = { username: "john", password: "password" };
$httpBackend.expectPOST("/signup", credentials).respond(200, { id: 1, name: "John Doe" });
var result;
AuthService.signup(credentials).then(function (user) {
result = user;
});
$httpBackend.flush();
expect(result).toEqual({ id: 1, name: "John Doe" });
});

it("should reject with an error message if the POST request fails", function () {
var credentials = { username: "john", password: "password" };
$httpBackend.expectPOST("/signup", credentials).respond(500);
var result;
AuthService.signup(credentials).catch(function (error) {
result = error;
});
$httpBackend.flush();
expect(result).toEqual({ message: "Invalid signup credentials." });
});
});

describe("login", function () {
it("should make a POST request to /login with the provided credentials and call onSuccessfulLogin if successful", function () {
var credentials = { username: "john", password: "password" };
$httpBackend.expectPOST("/login", credentials).respond(200, { id: 1, name: "John Doe" });
var result;
AuthService.login(credentials).then(function (user) {
result = user;
});
$httpBackend.flush();
expect(result).toEqual({ id: 1, name: "John Doe" });
});

it("should reject with an error message if the POST request fails", function () {
var credentials = { username: "john", password: "password" };
$httpBackend.expectPOST("/login", credentials).respond(500);
var result;
AuthService.login(credentials).catch(function (error) {
result = error;
});
$httpBackend.flush();
expect(result).toEqual({ message: "Invalid login credentials." });
});
});

describe("logout", function () {
it("should make a GET request to /logout and destroy the session if successful", function () {
Session.user = { id: 1, name: "John Doe" };
$httpBackend.expectGET("/logout").respond(200);
AuthService.logout();
$httpBackend.flush();
expect(Session.user).toBeNull();
});
});
});

describe("Session", function () {
describe("create", function () {
it("should set the sessionId and user properties", function () {
Session.create(1, { id: 1, name: "John Doe" });
expect(Session.id).toBe(1);
expect(Session.user).toEqual({ id: 1, name: "John Doe" });
});
});

describe("destroy", function () {
it("should set the sessionId and user properties to null", function () {
Session.destroy();
expect(Session.id).toBeNull();
expect(Session.user).toBeNull();
});
});
});
});

0 comments on commit 39dd8b2

Please sign in to comment.