diff options
| author | Syndamia <kamen.d.mladenov@protonmail.com> | 2021-01-31 11:03:33 +0200 |
|---|---|---|
| committer | Syndamia <kamen.d.mladenov@protonmail.com> | 2021-01-31 11:03:33 +0200 |
| commit | cc8e45328c9df90cd3535e34bf2e0bb34416e0f7 (patch) | |
| tree | 364d648586e8fbb691f9dedc1c983b10285970c5 | |
| parent | 157cd5f82aaa28b30dcfe5a4010e87bd90084c44 (diff) | |
| download | DevHive-cc8e45328c9df90cd3535e34bf2e0bb34416e0f7.tar DevHive-cc8e45328c9df90cd3535e34bf2e0bb34416e0f7.tar.gz DevHive-cc8e45328c9df90cd3535e34bf2e0bb34416e0f7.zip | |
Severely improved angular code consistency; moved (session) token logic in it's own service
22 files changed, 310 insertions, 266 deletions
diff --git a/src/DevHive.Angular/src/app/app-constants.module.ts b/src/DevHive.Angular/src/app/app-constants.module.ts index cbb1ec1..101ab44 100644 --- a/src/DevHive.Angular/src/app/app-constants.module.ts +++ b/src/DevHive.Angular/src/app/app-constants.module.ts @@ -13,4 +13,6 @@ export class AppConstants { public static PAGE_SIZE = 5; public static FALLBACK_PROFILE_ICON = 'assets/images/feed/profile-pic.png'; + + public static SESSION_TOKEN_KEY = 'UserCred'; } diff --git a/src/DevHive.Angular/src/app/components/error-bar/error-bar.component.ts b/src/DevHive.Angular/src/app/components/error-bar/error-bar.component.ts index c24448e..111bac8 100644 --- a/src/DevHive.Angular/src/app/components/error-bar/error-bar.component.ts +++ b/src/DevHive.Angular/src/app/components/error-bar/error-bar.component.ts @@ -1,6 +1,6 @@ -import {HttpErrorResponse} from '@angular/common/http'; +import { HttpErrorResponse } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; -import {IApiError} from 'src/interfaces/api-error'; +import { IApiError } from 'src/interfaces/api-error'; @Component({ selector: 'app-error-bar', @@ -10,14 +10,20 @@ import {IApiError} from 'src/interfaces/api-error'; export class ErrorBarComponent implements OnInit { public errorMsg = ''; - constructor() { } + constructor() + { } ngOnInit(): void { this.hideError(); } showError(error: HttpErrorResponse): void { - const test: IApiError = { type: '', title: 'Error!', status: 0, traceId: '' }; + const test: IApiError = { + type: '', + title: 'Error!', + status: 0, + traceId: '' + }; Object.assign(test, error.error); this.errorMsg = test.title; } diff --git a/src/DevHive.Angular/src/app/components/feed/feed.component.html b/src/DevHive.Angular/src/app/components/feed/feed.component.html index 052f7b3..342037c 100644 --- a/src/DevHive.Angular/src/app/components/feed/feed.component.html +++ b/src/DevHive.Angular/src/app/components/feed/feed.component.html @@ -19,7 +19,7 @@ <img id="top-bar-profile-pic" class="round-image" [src]="user.imageUrl" alt="" (click)="goToProfile()"> <form [formGroup]="createPostFormGroup" (ngSubmit)="createPost()"> <input id="top-bar-create-post" type="text" formControlName="newPostMessage" placeholder="What's on your mind?"/> - <input type="submit" style="display: none" /> + <input type="submit" style="display: none" /> <!--> You need this element, so when you press enter the request is sent <--!> </form> <a id="top-bar-open-chat" href=""> <img src="assets/images/feed/chat-pic.png" alt=""/> diff --git a/src/DevHive.Angular/src/app/components/feed/feed.component.ts b/src/DevHive.Angular/src/app/components/feed/feed.component.ts index a399717..f583078 100644 --- a/src/DevHive.Angular/src/app/components/feed/feed.component.ts +++ b/src/DevHive.Angular/src/app/components/feed/feed.component.ts @@ -1,14 +1,15 @@ -import { Component, OnInit, ViewChild } from '@angular/core'; +import { Component, OnInit } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { Router } from '@angular/router'; import { User } from 'src/models/identity/user'; import { UserService } from '../../services/user.service'; import { AppConstants } from 'src/app/app-constants.module'; -import {HttpErrorResponse} from '@angular/common/http'; -import {FeedService} from 'src/app/services/feed.service'; -import {Post} from 'src/models/post'; -import {FormBuilder, FormControl, FormGroup} from '@angular/forms'; -import {PostService} from 'src/app/services/post.service'; +import { HttpErrorResponse } from '@angular/common/http'; +import { FeedService } from 'src/app/services/feed.service'; +import { Post } from 'src/models/post'; +import { FormBuilder, FormControl, FormGroup } from '@angular/forms'; +import { PostService } from 'src/app/services/post.service'; +import { TokenService } from 'src/app/services/token.service'; @Component({ selector: 'app-feed', @@ -17,17 +18,18 @@ import {PostService} from 'src/app/services/post.service'; }) export class FeedComponent implements OnInit { private _title = 'Feed'; - private _timeLoaded: string; + private _timeLoaded: string; // we send the time to the api as a string public dataArrived = false; public user: User; - public posts: Post[] = []; + public posts: Post[]; public createPostFormGroup: FormGroup; - constructor(private _titleService: Title, private _fb: FormBuilder, private _router: Router, private _userService: UserService, private _feedService: FeedService, private _postService: PostService) { + constructor(private _titleService: Title, private _fb: FormBuilder, private _router: Router, private _userService: UserService, private _feedService: FeedService, private _postService: PostService, private _tokenService: TokenService) { this._titleService.setTitle(this._title); } ngOnInit(): void { + this.posts = []; this.user = this._userService.getDefaultUser(); const now = new Date(); @@ -40,17 +42,20 @@ export class FeedComponent implements OnInit { if (sessionStorage.getItem('UserCred')) { this._userService.getUserFromSessionStorageRequest().subscribe( - (res: object) => this.loadFeed(res), - (err: HttpErrorResponse) => this.bailOnBadToken() + (res: object) => { + Object.assign(this.user, res); + this.loadFeed(); + }, + (err: HttpErrorResponse) => { + this.logout(); + } ); } else { this._router.navigate(['/login']); } } - private loadFeed(res: object): void { - Object.assign(this.user, res); - + private loadFeed(): void { this._feedService.getUserFeedFromSessionStorageRequest(1, this._timeLoaded, AppConstants.PAGE_SIZE).subscribe( (result: object) => { this.posts = Object.values(result)[0]; @@ -63,17 +68,9 @@ export class FeedComponent implements OnInit { } private finishUserLoading(): void { - if (this.user.imageUrl === '') { - this.user.imageUrl = AppConstants.FALLBACK_PROFILE_ICON; - } this.dataArrived = true; } - private bailOnBadToken(): void { - this._userService.logoutUserFromSessionStorage(); - this._router.navigate(['/login']); - } - goToProfile(): void { this._router.navigate(['/profile/' + this.user.userName]); } @@ -83,17 +80,15 @@ export class FeedComponent implements OnInit { } logout(): void { - this._userService.logoutUserFromSessionStorage(); + this._tokenService.logoutUserFromSessionStorage(); this._router.navigate(['/login']); } createPost(): void { const postMessage = this.createPostFormGroup.get('newPostMessage')?.value; + this._postService.createPostFromSessionStorageRequest(postMessage).subscribe( (result: object) => { - this.createPostFormGroup.patchValue({ - newPostMessage: '' - }); this.goToProfile(); } ); diff --git a/src/DevHive.Angular/src/app/components/loading/loading.component.ts b/src/DevHive.Angular/src/app/components/loading/loading.component.ts index 4dff0cd..e203484 100644 --- a/src/DevHive.Angular/src/app/components/loading/loading.component.ts +++ b/src/DevHive.Angular/src/app/components/loading/loading.component.ts @@ -7,9 +7,9 @@ import { Component, OnInit } from '@angular/core'; }) export class LoadingComponent implements OnInit { - constructor() { } + constructor() + { } ngOnInit(): void { } - } diff --git a/src/DevHive.Angular/src/app/components/login/login.component.ts b/src/DevHive.Angular/src/app/components/login/login.component.ts index c424060..6e285db 100644 --- a/src/DevHive.Angular/src/app/components/login/login.component.ts +++ b/src/DevHive.Angular/src/app/components/login/login.component.ts @@ -1,11 +1,11 @@ -import { Component, ErrorHandler, OnInit, ViewChild } from '@angular/core'; +import { Component, OnInit, ViewChild } from '@angular/core'; import { FormGroup, FormBuilder, Validators, FormControl, AbstractControl } from '@angular/forms'; import { Router } from '@angular/router'; import { Title } from '@angular/platform-browser'; import { UserService } from 'src/app/services/user.service'; -import {AppConstants} from 'src/app/app-constants.module'; -import {HttpErrorResponse, HttpResponse} from '@angular/common/http'; -import {ErrorBarComponent} from '../error-bar/error-bar.component'; +import { HttpErrorResponse } from '@angular/common/http'; +import { ErrorBarComponent } from '../error-bar/error-bar.component'; +import { TokenService } from 'src/app/services/token.service'; @Component({ selector: 'app-login', @@ -15,9 +15,9 @@ import {ErrorBarComponent} from '../error-bar/error-bar.component'; export class LoginComponent implements OnInit { @ViewChild(ErrorBarComponent) private _errorBar: ErrorBarComponent; private _title = 'Login'; - loginUserFormGroup: FormGroup; + public loginUserFormGroup: FormGroup; - constructor(private _titleService: Title, private _fb: FormBuilder, private _router: Router, private _userService: UserService) { + constructor(private _titleService: Title, private _fb: FormBuilder, private _router: Router, private _userService: UserService, private _tokenService: TokenService) { this._titleService.setTitle(this._title); } @@ -35,16 +35,16 @@ export class LoginComponent implements OnInit { onSubmit(): void { this._errorBar.hideError(); this._userService.loginUserRequest(this.loginUserFormGroup).subscribe( - res => this.finishLogin(res), - (err: HttpErrorResponse) => this._errorBar.showError(err) + res => { + this._tokenService.setUserTokenToSessionStorage(res); + this._router.navigate(['/']); + }, + (err: HttpErrorResponse) => { + this._errorBar.showError(err); + } ); } - private finishLogin(res: object): void { - this._userService.setUserTokenToSessionStorage(res); - this._router.navigate(['/']); - } - onRedirectRegister(): void { this._router.navigate(['/register']); } diff --git a/src/DevHive.Angular/src/app/components/not-found/not-found.component.ts b/src/DevHive.Angular/src/app/components/not-found/not-found.component.ts index 157fb97..89a230d 100644 --- a/src/DevHive.Angular/src/app/components/not-found/not-found.component.ts +++ b/src/DevHive.Angular/src/app/components/not-found/not-found.component.ts @@ -1,5 +1,5 @@ import { Component, OnInit } from '@angular/core'; -import {Router} from '@angular/router'; +import { Router } from '@angular/router'; @Component({ selector: 'app-not-found', diff --git a/src/DevHive.Angular/src/app/components/post/post.component.ts b/src/DevHive.Angular/src/app/components/post/post.component.ts index 7a6b5c0..43ea058 100644 --- a/src/DevHive.Angular/src/app/components/post/post.component.ts +++ b/src/DevHive.Angular/src/app/components/post/post.component.ts @@ -1,12 +1,10 @@ import { Component, Input, OnInit } from '@angular/core'; -import {Router} from '@angular/router'; +import { Router } from '@angular/router'; import { Guid } from 'guid-typescript'; -import {AppConstants} from 'src/app/app-constants.module'; -import {FeedService} from 'src/app/services/feed.service'; -import {PostService} from 'src/app/services/post.service'; -import {UserService} from 'src/app/services/user.service'; +import { PostService } from 'src/app/services/post.service'; +import { UserService } from 'src/app/services/user.service'; import { User } from 'src/models/identity/user'; -import {Post} from 'src/models/post'; +import { Post } from 'src/models/post'; @Component({ selector: 'app-post', @@ -14,15 +12,15 @@ import {Post} from 'src/models/post'; styleUrls: ['./post.component.css'], }) export class PostComponent implements OnInit { + public loaded = false; public user: User; public post: Post; public votesNumber: number; public timeCreated: string; - public loaded = false; @Input() paramId: string; constructor(private _postService: PostService, private _userService: UserService, private _router: Router) - {} + { } ngOnInit(): void { this.post = this._postService.getDefaultPost(); @@ -31,11 +29,12 @@ export class PostComponent implements OnInit { this._postService.getPostRequest(Guid.parse(this.paramId)).subscribe( (result: object) => { Object.assign(this.post, result); + this.votesNumber = 23; + this.timeCreated = new Date(this.post.timeCreated).toLocaleString('en-GB'); this.loadUser(); } ); - this.votesNumber = 23; } private loadUser(): void { diff --git a/src/DevHive.Angular/src/app/components/profile-settings/profile-settings.component.ts b/src/DevHive.Angular/src/app/components/profile-settings/profile-settings.component.ts index 83a5501..3460842 100644 --- a/src/DevHive.Angular/src/app/components/profile-settings/profile-settings.component.ts +++ b/src/DevHive.Angular/src/app/components/profile-settings/profile-settings.component.ts @@ -1,17 +1,17 @@ -import {Location} from '@angular/common'; -import {HttpErrorResponse} from '@angular/common/http'; +import { Location } from '@angular/common'; +import { HttpErrorResponse } from '@angular/common/http'; import { Component, OnInit, ViewChild } from '@angular/core'; -import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms'; -import {Router} from '@angular/router'; -import {AppConstants} from 'src/app/app-constants.module'; -import {LanguageService} from 'src/app/services/language.service'; -import {UserService} from 'src/app/services/user.service'; -import {TechnologyService} from 'src/app/services/technology.service'; -import {User} from 'src/models/identity/user'; -import {ErrorBarComponent} from '../error-bar/error-bar.component'; -import {SuccessBarComponent} from '../success-bar/success-bar.component'; -import {Language} from 'src/models/language'; -import {Technology} from 'src/models/technology'; +import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; +import { Router } from '@angular/router'; +import { LanguageService } from 'src/app/services/language.service'; +import { UserService } from 'src/app/services/user.service'; +import { TechnologyService } from 'src/app/services/technology.service'; +import { User } from 'src/models/identity/user'; +import { ErrorBarComponent } from '../error-bar/error-bar.component'; +import { SuccessBarComponent } from '../success-bar/success-bar.component'; +import { Language } from 'src/models/language'; +import { Technology } from 'src/models/technology'; +import { TokenService } from 'src/app/services/token.service'; @Component({ selector: 'app-profile-settings', @@ -22,26 +22,34 @@ export class ProfileSettingsComponent implements OnInit { @ViewChild(ErrorBarComponent) private _errorBar: ErrorBarComponent; @ViewChild(SuccessBarComponent) private _successBar: SuccessBarComponent; private _urlUsername: string; - public updateUserFormGroup: FormGroup; public dataArrived = false; - public user: User; public deleteAccountConfirm = false; public showLanguages = false; - public availableLanguages: Language[] = []; public showTechnologies = false; - public availableTechnologies: Technology[] = []; + public updateUserFormGroup: FormGroup; + public user: User; + public availableLanguages: Language[]; + public availableTechnologies: Technology[]; - constructor(private _router: Router, private _userService: UserService, private _languageService: LanguageService, private _technologyService: TechnologyService, private _fb: FormBuilder, private _location: Location) + constructor(private _router: Router, private _userService: UserService, private _languageService: LanguageService, private _technologyService: TechnologyService, private _tokenService: TokenService, private _fb: FormBuilder, private _location: Location) { } ngOnInit(): void { this._urlUsername = this._router.url.substring(9); this._urlUsername = this._urlUsername.substring(0, this._urlUsername.length - 9); + this.user = this._userService.getDefaultUser(); + this.availableLanguages = []; + this.availableTechnologies = []; this._userService.getUserByUsernameRequest(this._urlUsername).subscribe( - (res: object) => this.finishUserLoading(res), - (err: HttpErrorResponse) => { this._router.navigate(['/not-found']); } + (res: object) => { + Object.assign(this.user, res); + this.finishUserLoading(); + }, + (err: HttpErrorResponse) => { + this._router.navigate(['/not-found']); + } ); this._languageService.getAllLanguagesWithSessionStorageRequest().subscribe( @@ -56,12 +64,7 @@ export class ProfileSettingsComponent implements OnInit { ); } - private finishUserLoading(res: object): void { - Object.assign(this.user, res); - if (this.user.imageUrl === '') { - this.user.imageUrl = AppConstants.FALLBACK_PROFILE_ICON; - } - + private finishUserLoading(): void { if (sessionStorage.getItem('UserCred')) { const userFromToken: User = this._userService.getDefaultUser(); @@ -77,7 +80,9 @@ export class ProfileSettingsComponent implements OnInit { this.goToProfile(); } }, - (err: HttpErrorResponse) => this.bailOnBadToken() + (err: HttpErrorResponse) => { + this.logout(); + } ); } else { @@ -121,11 +126,13 @@ export class ProfileSettingsComponent implements OnInit { technologies: new FormControl('') }); - this.getLanguagesForShowing() - .then(value => this.updateUserFormGroup.patchValue({ languageInput : value })); + this.getLanguagesForShowing().then(value => { + this.updateUserFormGroup.patchValue({ languageInput : value }); + }); - this.getTechnologiesForShowing() - .then(value => this.updateUserFormGroup.patchValue({ technologyInput : value })); + this.getTechnologiesForShowing().then(value => { + this.updateUserFormGroup.patchValue({ technologyInput : value }); + }); this.updateUserFormGroup.valueChanges.subscribe(() => { this._successBar?.hideMsg(); @@ -134,28 +141,21 @@ export class ProfileSettingsComponent implements OnInit { } private getLanguagesForShowing(): Promise<string> { - return new Promise(resolve => - this._languageService.getFullLanguagesFromIncomplete(this.user.languages) - .then(value => { - this.user.languages = value; - resolve(value.map(x => x.name).join(' ')); - }) - ); + return new Promise(resolve => { + this._languageService.getFullLanguagesFromIncomplete(this.user.languages).then(value => { + this.user.languages = value; + resolve(value.map(x => x.name).join(' ')); + }); + }); } private getTechnologiesForShowing(): Promise<string> { - return new Promise(resolve => - this._technologyService.getFullTechnologiesFromIncomplete(this.user.technologies) - .then(value => { - this.user.technologies = value; - resolve(value.map(x => x.name).join(' ')); - }) - ); - } - - private bailOnBadToken(): void { - this._userService.logoutUserFromSessionStorage(); - this._router.navigate(['/login']); + return new Promise(resolve => { + this._technologyService.getFullTechnologiesFromIncomplete(this.user.technologies).then(value => { + this.user.technologies = value; + resolve(value.map(x => x.name).join(' ')); + }); + }); } onSubmit(): void { @@ -166,8 +166,12 @@ export class ProfileSettingsComponent implements OnInit { this.patchTechnologiesControl(); this._userService.putUserFromSessionStorageRequest(this.updateUserFormGroup, this.user.roles, this.user.friends).subscribe( - res => this._successBar.showMsg('Profile updated successfully!'), - (err: HttpErrorResponse) => this._errorBar.showError(err) + res => { + this._successBar.showMsg('Profile updated successfully!'); + }, + (err: HttpErrorResponse) => { + this._errorBar.showError(err); + } ); } @@ -227,7 +231,6 @@ export class ProfileSettingsComponent implements OnInit { } } - goToProfile(): void { this._router.navigate([this._router.url.substring(0, this._router.url.length - 9)]); } @@ -241,7 +244,7 @@ export class ProfileSettingsComponent implements OnInit { } logout(): void { - this._userService.logoutUserFromSessionStorage(); + this._tokenService.logoutUserFromSessionStorage(); this.goToProfile(); } @@ -257,10 +260,11 @@ export class ProfileSettingsComponent implements OnInit { if (this.deleteAccountConfirm) { this._userService.deleteUserFromSessionStorageRequest().subscribe( (res: object) => { - this._userService.logoutUserFromSessionStorage(); - this._router.navigate(['/login']); + this.logout(); }, - (err: HttpErrorResponse) => console.log(err) + (err: HttpErrorResponse) => { + this._errorBar.showError(err); + } ); } else { diff --git a/src/DevHive.Angular/src/app/components/profile/profile.component.ts b/src/DevHive.Angular/src/app/components/profile/profile.component.ts index 620c931..04e49f7 100644 --- a/src/DevHive.Angular/src/app/components/profile/profile.component.ts +++ b/src/DevHive.Angular/src/app/components/profile/profile.component.ts @@ -3,12 +3,13 @@ import { Router } from '@angular/router'; import { UserService } from 'src/app/services/user.service'; import { User } from 'src/models/identity/user'; import { AppConstants } from 'src/app/app-constants.module'; -import {HttpErrorResponse} from '@angular/common/http'; -import {Location} from '@angular/common'; -import {LanguageService} from 'src/app/services/language.service'; -import {TechnologyService} from 'src/app/services/technology.service'; -import {Post} from 'src/models/post'; -import {FeedService} from 'src/app/services/feed.service'; +import { HttpErrorResponse } from '@angular/common/http'; +import { Location } from '@angular/common'; +import { LanguageService } from 'src/app/services/language.service'; +import { TechnologyService } from 'src/app/services/technology.service'; +import { Post } from 'src/models/post'; +import { FeedService } from 'src/app/services/feed.service'; +import { TokenService } from 'src/app/services/token.service'; @Component({ selector: 'app-profile', @@ -20,9 +21,9 @@ export class ProfileComponent implements OnInit { public loggedInUser = false; public dataArrived = false; public user: User; - public userPosts: Post[] = []; + public userPosts: Post[]; - constructor(private _router: Router, private _userService: UserService, private _languageService: LanguageService, private _technologyService: TechnologyService, private _feedService: FeedService, private _location: Location) + constructor(private _router: Router, private _userService: UserService, private _languageService: LanguageService, private _technologyService: TechnologyService, private _feedService: FeedService, private _location: Location, private _tokenService: TokenService) { } private setDefaultUser(): void { @@ -32,23 +33,26 @@ export class ProfileComponent implements OnInit { ngOnInit(): void { this._urlUsername = this._router.url.substring(9); this.user = this._userService.getDefaultUser(); + this.userPosts = []; this._userService.getUserByUsernameRequest(this._urlUsername).subscribe( - (res: object) => this.loadLanguages(res), - (err: HttpErrorResponse) => { this._router.navigate(['/not-found']); } + (res: object) => { + Object.assign(this.user, res); + this.loadLanguages(); + }, + (err: HttpErrorResponse) => { + this._router.navigate(['/not-found']); + } ); } - private loadLanguages(res: object): void { - Object.assign(this.user, res); - + private loadLanguages(): void { if (this.user.languages.length > 0) { // When user has languages, get their names and load technologies - this._languageService.getFullLanguagesFromIncomplete(this.user.languages) - .then(value => { - this.user.languages = value; - this.loadTechnologies(); - }); + this._languageService.getFullLanguagesFromIncomplete(this.user.languages).then(value => { + this.user.languages = value; + this.loadTechnologies(); + }); } else { this.loadTechnologies(); @@ -58,11 +62,10 @@ export class ProfileComponent implements OnInit { private loadTechnologies(): void { if (this.user.technologies.length > 0) { // When user has technologies, get their names and then load posts - this._technologyService.getFullTechnologiesFromIncomplete(this.user.technologies) - .then(value => { - this.user.technologies = value; - this.loadPosts(); - }); + this._technologyService.getFullTechnologiesFromIncomplete(this.user.technologies).then(value => { + this.user.technologies = value; + this.loadPosts(); + }); } else { this.loadPosts(); @@ -85,10 +88,6 @@ export class ProfileComponent implements OnInit { } private finishUserLoading(): void { - if (this.user.imageUrl === '') { - this.user.imageUrl = AppConstants.FALLBACK_PROFILE_ICON; - } - if (sessionStorage.getItem('UserCred')) { const userFromToken: User = this._userService.getDefaultUser(); @@ -101,7 +100,9 @@ export class ProfileComponent implements OnInit { } this.dataArrived = true; }, - (err: HttpErrorResponse) => this.bailOnBadToken() + (err: HttpErrorResponse) => { + this.logout(); + } ); } else { @@ -109,11 +110,6 @@ export class ProfileComponent implements OnInit { } } - private bailOnBadToken(): void { - this._userService.logoutUserFromSessionStorage(); - this._router.navigate(['/login']); - } - goBack(): void { const currURL = this._location.path(); this._location.back(); @@ -127,7 +123,7 @@ export class ProfileComponent implements OnInit { } logout(): void { - this._userService.logoutUserFromSessionStorage(); + this._tokenService.logoutUserFromSessionStorage(); // Reload the page this._router.routeReuseStrategy.shouldReuseRoute = () => false; diff --git a/src/DevHive.Angular/src/app/components/register/register.component.ts b/src/DevHive.Angular/src/app/components/register/register.component.ts index 832d176..36eaa55 100644 --- a/src/DevHive.Angular/src/app/components/register/register.component.ts +++ b/src/DevHive.Angular/src/app/components/register/register.component.ts @@ -1,10 +1,11 @@ -import {HttpErrorResponse} from '@angular/common/http'; +import { HttpErrorResponse } from '@angular/common/http'; import { Component, OnInit, ViewChild } from '@angular/core'; import { AbstractControl, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; import { Title } from '@angular/platform-browser'; import { Router } from '@angular/router'; +import { TokenService } from 'src/app/services/token.service'; import { UserService } from 'src/app/services/user.service'; -import {ErrorBarComponent} from '../error-bar/error-bar.component'; +import { ErrorBarComponent } from '../error-bar/error-bar.component'; @Component({ selector: 'app-register', @@ -16,7 +17,7 @@ export class RegisterComponent implements OnInit { private _title = 'Register'; public registerUserFormGroup: FormGroup; - constructor(private _titleService: Title, private _fb: FormBuilder, private _router: Router, private _userService: UserService) { + constructor(private _titleService: Title, private _fb: FormBuilder, private _router: Router, private _userService: UserService, private _tokenService: TokenService) { this._titleService.setTitle(this._title); } @@ -50,16 +51,15 @@ export class RegisterComponent implements OnInit { onSubmit(): void { this._userService.registerUserRequest(this.registerUserFormGroup).subscribe( - res => this.finishRegister(res), - (err: HttpErrorResponse) => this._errorBar.showError(err) + res => { + this._tokenService.setUserTokenToSessionStorage(res); + this._router.navigate(['/']); + }, + (err: HttpErrorResponse) => { + this._errorBar.showError(err); + } ); } - - private finishRegister(res: object): void { - this._userService.setUserTokenToSessionStorage(res); - this._router.navigate(['/']); - } - onRedirectLogin(): void { this._router.navigate(['/login']); } diff --git a/src/DevHive.Angular/src/app/components/success-bar/success-bar.component.ts b/src/DevHive.Angular/src/app/components/success-bar/success-bar.component.ts index f7db0e2..f7c7e54 100644 --- a/src/DevHive.Angular/src/app/components/success-bar/success-bar.component.ts +++ b/src/DevHive.Angular/src/app/components/success-bar/success-bar.component.ts @@ -8,7 +8,8 @@ import { Component, OnInit } from '@angular/core'; export class SuccessBarComponent implements OnInit { public successMsg = ''; - constructor() { } + constructor() + { } ngOnInit(): void { this.hideMsg(); diff --git a/src/DevHive.Angular/src/app/services/feed.service.ts b/src/DevHive.Angular/src/app/services/feed.service.ts index cb82bcd..d160f6d 100644 --- a/src/DevHive.Angular/src/app/services/feed.service.ts +++ b/src/DevHive.Angular/src/app/services/feed.service.ts @@ -1,24 +1,28 @@ -import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http'; -import {Injectable} from '@angular/core'; -import {Guid} from 'guid-typescript'; -import {Observable} from 'rxjs'; -import {IJWTPayload} from 'src/interfaces/jwt-payload'; -import {AppConstants} from '../app-constants.module'; -import jwt_decode from 'jwt-decode'; -import {IUserCredentials} from 'src/interfaces/user-credentials'; +import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; +import { Injectable } from '@angular/core'; +import { Guid } from 'guid-typescript'; +import { Observable } from 'rxjs'; +import { AppConstants } from '../app-constants.module'; +import { TokenService } from './token.service'; @Injectable({ providedIn: 'root' }) export class FeedService { - constructor(private http: HttpClient) { } + constructor(private _http: HttpClient, private _tokenService: TokenService) + { } + + /* Requests from session storage */ getUserFeedFromSessionStorageRequest(pageNumber: number, firstTimeIssued: string, pageSize: number): Observable<object> { - const jwt: IJWTPayload = { token: sessionStorage.getItem('UserCred') ?? '' }; - const userCred = jwt_decode<IUserCredentials>(jwt.token); - return this.getUserFeedRequest(userCred.ID, jwt.token, pageNumber, firstTimeIssued, pageSize); + const token = this._tokenService.getTokenFromSessionStorage(); + const userId = this._tokenService.getUserIdFromSessionStorageToken(); + + return this.getUserFeedRequest(userId, token, pageNumber, firstTimeIssued, pageSize); } + /* Feed requests */ + getUserFeedRequest(userId: Guid, authToken: string, pageNumber: number, firstTimeIssued: string, pageSize: number): Observable<object> { const body = { pageNumber: pageNumber, @@ -29,7 +33,7 @@ export class FeedService { params: new HttpParams().set('UserId', userId.toString()), headers: new HttpHeaders().set('Authorization', 'Bearer ' + authToken) }; - return this.http.post(AppConstants.API_FEED_URL + '/GetPosts', body, options); + return this._http.post(AppConstants.API_FEED_URL + '/GetPosts', body, options); } getUserPostsRequest(userName: string, pageNumber: number, firstTimeIssued: string, pageSize: number): Observable<object> { @@ -41,6 +45,6 @@ export class FeedService { const options = { params: new HttpParams().set('UserName', userName) }; - return this.http.post(AppConstants.API_FEED_URL + '/GetUserPosts', body, options); + return this._http.post(AppConstants.API_FEED_URL + '/GetUserPosts', body, options); } } diff --git a/src/DevHive.Angular/src/app/services/language.service.ts b/src/DevHive.Angular/src/app/services/language.service.ts index 65012e9..49be537 100644 --- a/src/DevHive.Angular/src/app/services/language.service.ts +++ b/src/DevHive.Angular/src/app/services/language.service.ts @@ -1,33 +1,40 @@ -import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http'; -import {Injectable} from '@angular/core'; -import {Guid} from 'guid-typescript'; -import {Observable} from 'rxjs'; -import {Language} from 'src/models/language'; -import {AppConstants} from '../app-constants.module'; +import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; +import { Injectable } from '@angular/core'; +import { Guid } from 'guid-typescript'; +import { Observable } from 'rxjs'; +import { Language } from 'src/models/language'; +import { AppConstants } from '../app-constants.module'; +import { TokenService } from './token.service'; @Injectable({ providedIn: 'root' }) export class LanguageService { - constructor(private http: HttpClient) { } + constructor(private _http: HttpClient, private _tokenService: TokenService) + { } + + /* Requests from session storage */ + + getAllLanguagesWithSessionStorageRequest(): Observable<object> { + const token = this._tokenService.getTokenFromSessionStorage(); + + return this.getAllLanguagesRequest(token); + } + + /* Language requests */ getLanguageRequest(langId: Guid): Observable<object> { const options = { params: new HttpParams().set('Id', langId.toString()), }; - return this.http.get(AppConstants.API_LANGUAGE_URL, options); - } - - getAllLanguagesWithSessionStorageRequest(): Observable<object> { - const token = sessionStorage.getItem('UserCred') ?? ''; - return this.getAllLanguagesRequest(token); + return this._http.get(AppConstants.API_LANGUAGE_URL, options); } getAllLanguagesRequest(authToken: string): Observable<object> { const options = { headers: new HttpHeaders().set('Authorization', 'Bearer ' + authToken) }; - return this.http.get(AppConstants.API_LANGUAGE_URL + '/GetLanguages', options); + return this._http.get(AppConstants.API_LANGUAGE_URL + '/GetLanguages', options); } getFullLanguagesFromIncomplete(givenLanguages: Language[]): Promise<Language[]> { diff --git a/src/DevHive.Angular/src/app/services/post.service.ts b/src/DevHive.Angular/src/app/services/post.service.ts index c81aca5..a35a323 100644 --- a/src/DevHive.Angular/src/app/services/post.service.ts +++ b/src/DevHive.Angular/src/app/services/post.service.ts @@ -1,29 +1,33 @@ -import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http'; -import {Injectable} from '@angular/core'; -import {Guid} from 'guid-typescript'; -import {Observable} from 'rxjs'; -import {Post} from 'src/models/post'; -import {AppConstants} from '../app-constants.module'; -import {UserService} from './user.service'; +import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; +import { Injectable } from '@angular/core'; +import { Guid } from 'guid-typescript'; +import { Observable } from 'rxjs'; +import { Post } from 'src/models/post'; +import { AppConstants } from '../app-constants.module'; +import { TokenService } from './token.service'; @Injectable({ providedIn: 'root' }) export class PostService { - constructor(private http: HttpClient, private _userService: UserService) + constructor(private _http: HttpClient, private _tokenService: TokenService) { } getDefaultPost(): Post { return new Post(Guid.createEmpty(), 'Gosho', 'Trapov', 'gosho_trapov', 'Your opinion on my idea?', new Date()); } + /* Requests from session storage */ + createPostFromSessionStorageRequest(postMessage: string): Observable<object> { - const token = sessionStorage.getItem('UserCred') ?? ''; - const userId = this._userService.getUserIdFromSessionStorageToken(); + const userId = this._tokenService.getUserIdFromSessionStorageToken(); + const token = this._tokenService.getTokenFromSessionStorage(); return this.createPostRequest(userId, token, postMessage); } + /* Post requests */ + createPostRequest(userId: Guid, authToken: string, postMessage: string): Observable<object> { const body = { message: postMessage, @@ -33,15 +37,13 @@ export class PostService { params: new HttpParams().set('UserId', userId.toString()), headers: new HttpHeaders().set('Authorization', 'Bearer ' + authToken) }; - return this.http.post(AppConstants.API_POST_URL, body, options); - + return this._http.post(AppConstants.API_POST_URL, body, options); } getPostRequest(id: Guid): Observable<object> { const options = { params: new HttpParams().set('Id', id.toString()) }; - return this.http.get(AppConstants.API_POST_URL, options); + return this._http.get(AppConstants.API_POST_URL, options); } } - diff --git a/src/DevHive.Angular/src/app/services/technology.service.ts b/src/DevHive.Angular/src/app/services/technology.service.ts index 90f90d6..3d0829b 100644 --- a/src/DevHive.Angular/src/app/services/technology.service.ts +++ b/src/DevHive.Angular/src/app/services/technology.service.ts @@ -1,33 +1,40 @@ -import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http'; -import {Injectable} from '@angular/core'; -import {Guid} from 'guid-typescript'; -import {Observable} from 'rxjs'; -import {Technology} from 'src/models/technology'; -import {AppConstants} from '../app-constants.module'; +import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; +import { Injectable } from '@angular/core'; +import { Guid } from 'guid-typescript'; +import { Observable } from 'rxjs'; +import { Technology } from 'src/models/technology'; +import { AppConstants } from '../app-constants.module'; +import { TokenService } from './token.service'; @Injectable({ providedIn: 'root' }) export class TechnologyService { - constructor(private http: HttpClient) { } + constructor(private _http: HttpClient, private _tokenService: TokenService) + { } + + /* Requests from session storage */ + + getAllTechnologiesWithSessionStorageRequest(): Observable<object> { + const token = this._tokenService.getTokenFromSessionStorage(); + + return this.getAllTechnologiesRequest(token); + } + + /* Technology requests */ getTechnologyRequest(techId: Guid): Observable<object> { const options = { params: new HttpParams().set('Id', techId.toString()) }; - return this.http.get(AppConstants.API_TECHNOLOGY_URL, options); - } - - getAllTechnologiesWithSessionStorageRequest(): Observable<object> { - const token = sessionStorage.getItem('UserCred') ?? ''; - return this.getAllTechnologiesRequest(token); + return this._http.get(AppConstants.API_TECHNOLOGY_URL, options); } getAllTechnologiesRequest(authToken: string): Observable<object> { const options = { headers: new HttpHeaders().set('Authorization', 'Bearer ' + authToken) }; - return this.http.get(AppConstants.API_TECHNOLOGY_URL + '/GetTechnologies', options); + return this._http.get(AppConstants.API_TECHNOLOGY_URL + '/GetTechnologies', options); } getFullTechnologiesFromIncomplete(givenTechnologies: Technology[]): Promise<Technology[]> { @@ -56,5 +63,4 @@ export class TechnologyService { } }); } - } diff --git a/src/DevHive.Angular/src/app/services/token.service.ts b/src/DevHive.Angular/src/app/services/token.service.ts new file mode 100644 index 0000000..8131228 --- /dev/null +++ b/src/DevHive.Angular/src/app/services/token.service.ts @@ -0,0 +1,38 @@ +import { Injectable } from '@angular/core'; +import { Guid } from 'guid-typescript'; +import jwt_decode from 'jwt-decode'; +import { IJWTPayload } from 'src/interfaces/jwt-payload'; +import { IUserCredentials } from 'src/interfaces/user-credentials'; +import { AppConstants } from '../app-constants.module'; + +@Injectable({ + providedIn: 'root' +}) +export class TokenService { + constructor() + { } + + /* Session storage */ + + setUserTokenToSessionStorage(response: object): void { + const token = JSON.stringify(response); + sessionStorage.setItem(AppConstants.SESSION_TOKEN_KEY, token.substr(10, token.length - 12)); + } + + getTokenFromSessionStorage(): string { + return sessionStorage.getItem(AppConstants.SESSION_TOKEN_KEY) ?? ''; + } + + getUserIdFromSessionStorageToken(): Guid { + const jwt: IJWTPayload = { + token: this.getTokenFromSessionStorage() + }; + const userCred = jwt_decode<IUserCredentials>(jwt.token); + + return userCred.ID; + } + + logoutUserFromSessionStorage(): void { + sessionStorage.removeItem(AppConstants.SESSION_TOKEN_KEY); + } +} diff --git a/src/DevHive.Angular/src/app/services/user.service.ts b/src/DevHive.Angular/src/app/services/user.service.ts index 128e94b..5448313 100644 --- a/src/DevHive.Angular/src/app/services/user.service.ts +++ b/src/DevHive.Angular/src/app/services/user.service.ts @@ -1,75 +1,59 @@ import { Injectable } from '@angular/core'; -import {Guid} from 'guid-typescript'; +import { Guid } from 'guid-typescript'; import { User } from '../../models/identity/user'; -import jwt_decode from 'jwt-decode'; -import { IJWTPayload } from '../../interfaces/jwt-payload'; -import { IUserCredentials } from '../../interfaces/user-credentials'; import { FormGroup } from '@angular/forms'; import { AppConstants } from 'src/app/app-constants.module'; -import {HttpClient, HttpErrorResponse, HttpHeaders, HttpParams} from '@angular/common/http'; -import {Observable} from 'rxjs'; -import {Role} from 'src/models/identity/role'; -import {Friend} from 'src/models/identity/friend'; +import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; +import { Observable } from 'rxjs'; +import { Role } from 'src/models/identity/role'; +import { Friend } from 'src/models/identity/friend'; +import { TokenService } from './token.service'; @Injectable({ providedIn: 'root' }) export class UserService { - constructor(private http: HttpClient) { } + constructor(private _http: HttpClient, private _tokenService: TokenService) + { } getDefaultUser(): User { return new User(Guid.createEmpty(), 'gosho_trapov', 'Gosho', 'Trapov', 'gotra@bg.com', AppConstants.FALLBACK_PROFILE_ICON, [], [], [], []); } - getUserIdFromSessionStorageToken(): Guid { - const jwt: IJWTPayload = { token: sessionStorage.getItem('UserCred') ?? '' }; - const userCred = jwt_decode<IUserCredentials>(jwt.token); - return userCred.ID; - } - - setUserTokenToSessionStorage(response: object): void { - const token = JSON.stringify(response); - sessionStorage.setItem('UserCred', token.substr(10, token.length - 12)); - } + /* Requests from session storage */ getUserFromSessionStorageRequest(): Observable<object> { - // Get the token and userid from session storage - const jwt: IJWTPayload = { token: sessionStorage.getItem('UserCred') ?? '' }; - const userCred = jwt_decode<IUserCredentials>(jwt.token); + const userId = this._tokenService.getUserIdFromSessionStorageToken(); + const token = this._tokenService.getTokenFromSessionStorage(); - return this.getUserRequest(userCred.ID, jwt.token); + return this.getUserRequest(userId, token); } putUserFromSessionStorageRequest(updateUserFormGroup: FormGroup, userRoles: Role[], userFriends: Friend[]): Observable<object> { - // Get the token and userid from session storage - const jwt: IJWTPayload = { token: sessionStorage.getItem('UserCred') ?? '' }; - const userCred = jwt_decode<IUserCredentials>(jwt.token); + const userId = this._tokenService.getUserIdFromSessionStorageToken(); + const token = this._tokenService.getTokenFromSessionStorage(); - return this.putUserRequest(userCred.ID, jwt.token, updateUserFormGroup, userRoles, userFriends); + return this.putUserRequest(userId, token, updateUserFormGroup, userRoles, userFriends); } deleteUserFromSessionStorageRequest(): Observable<object> { - // Get the token and userid from session storage - const jwt: IJWTPayload = { token: sessionStorage.getItem('UserCred') ?? '' }; - const userCred = jwt_decode<IUserCredentials>(jwt.token); + const userId = this._tokenService.getUserIdFromSessionStorageToken(); + const token = this._tokenService.getTokenFromSessionStorage(); - return this.deleteUserRequest(userCred.ID, jwt.token); + return this.deleteUserRequest(userId, token); } - logoutUserFromSessionStorage(): void { - sessionStorage.removeItem('UserCred'); - } + /* User requests */ loginUserRequest(loginUserFormGroup: FormGroup): Observable<object> { const body = { UserName: loginUserFormGroup.get('username')?.value, Password: loginUserFormGroup.get('password')?.value - }; - return this.http.post(AppConstants.API_USER_LOGIN_URL, body); + }; + return this._http.post(AppConstants.API_USER_LOGIN_URL, body); } registerUserRequest(registerUserFormGroup: FormGroup): Observable<object> { - // TODO?: add a check for form data validity const body = { UserName: registerUserFormGroup.get('username')?.value, Email: registerUserFormGroup.get('email')?.value, @@ -77,7 +61,7 @@ export class UserService { LastName: registerUserFormGroup.get('lastName')?.value, Password: registerUserFormGroup.get('password')?.value }; - return this.http.post(AppConstants.API_USER_REGISTER_URL, body); + return this._http.post(AppConstants.API_USER_REGISTER_URL, body); } getUserRequest(userId: Guid, authToken: string): Observable<object> { @@ -85,14 +69,14 @@ export class UserService { params: new HttpParams().set('Id', userId.toString()), headers: new HttpHeaders().set('Authorization', 'Bearer ' + authToken) }; - return this.http.get(AppConstants.API_USER_URL, options); + return this._http.get(AppConstants.API_USER_URL, options); } getUserByUsernameRequest(username: string): Observable<object> { const options = { - params: new HttpParams().set('UserName', username), + params: new HttpParams().set(AppConstants.SESSION_TOKEN_KEY, username), }; - return this.http.get(AppConstants.API_USER_URL + '/GetUser', options); + return this._http.get(AppConstants.API_USER_URL + '/GetUser', options); } putUserRequest(userId: Guid, authToken: string, updateUserFormGroup: FormGroup, userRoles: Role[], userFriends: Friend[]): Observable<object> { @@ -111,7 +95,7 @@ export class UserService { params: new HttpParams().set('Id', userId.toString()), headers: new HttpHeaders().set('Authorization', 'Bearer ' + authToken) }; - return this.http.put(AppConstants.API_USER_URL, body, options); + return this._http.put(AppConstants.API_USER_URL, body, options); } deleteUserRequest(userId: Guid, authToken: string): Observable<object> { @@ -119,6 +103,6 @@ export class UserService { params: new HttpParams().set('Id', userId.toString()), headers: new HttpHeaders().set('Authorization', 'Bearer ' + authToken) }; - return this.http.delete(AppConstants.API_USER_URL, options); + return this._http.delete(AppConstants.API_USER_URL, options); } } diff --git a/src/DevHive.Angular/src/models/identity/user.ts b/src/DevHive.Angular/src/models/identity/user.ts index f7b922c..020a403 100644 --- a/src/DevHive.Angular/src/models/identity/user.ts +++ b/src/DevHive.Angular/src/models/identity/user.ts @@ -1,8 +1,8 @@ import { Guid } from 'guid-typescript'; -import {Language} from '../language'; -import {Technology} from '../technology'; -import {Friend} from './friend'; -import {Role} from './role'; +import { Language } from '../language'; +import { Technology } from '../technology'; +import { Friend } from './friend'; +import { Role } from './role'; export class User { private _id : Guid; diff --git a/src/DevHive.Angular/src/models/language.ts b/src/DevHive.Angular/src/models/language.ts index 9ae6814..e3aa61e 100644 --- a/src/DevHive.Angular/src/models/language.ts +++ b/src/DevHive.Angular/src/models/language.ts @@ -1,4 +1,4 @@ -import {Guid} from 'guid-typescript'; +import { Guid } from 'guid-typescript'; export class Language { public id: Guid; diff --git a/src/DevHive.Angular/src/models/post.ts b/src/DevHive.Angular/src/models/post.ts index 2d7d79f..4c6ac20 100644 --- a/src/DevHive.Angular/src/models/post.ts +++ b/src/DevHive.Angular/src/models/post.ts @@ -1,4 +1,4 @@ -import {Guid} from 'guid-typescript'; +import { Guid } from 'guid-typescript'; export class Post { private _postId: Guid; diff --git a/src/DevHive.Angular/src/models/technology.ts b/src/DevHive.Angular/src/models/technology.ts index 4235a86..1869d14 100644 --- a/src/DevHive.Angular/src/models/technology.ts +++ b/src/DevHive.Angular/src/models/technology.ts @@ -1,4 +1,4 @@ -import {Guid} from 'guid-typescript'; +import { Guid } from 'guid-typescript'; export class Technology { public id: Guid; |
