Skip to content

Instantly share code, notes, and snippets.

@carloszan
Last active January 11, 2021 00:55
Show Gist options
  • Save carloszan/e28f4c2291c9021a82b40d7a6f97f742 to your computer and use it in GitHub Desktop.
Save carloszan/e28f4c2291c9021a82b40d7a6f97f742 to your computer and use it in GitHub Desktop.
ng-auth
<li class="nav-item active" *ngIf="isLogged">
<a class="nav-link" href="/" style="text-transform: uppercase;" (click)="logout()">Deslogar
<span class="sr-only">(current)</span>
</a>
</li>
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(
private userService: UserService
) {}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
// add auth header with jwt if user is logged in and request is to the api url
const tokenObj = this.userService.tokenValue;
const isLoggedIn = tokenObj && tokenObj.token;
const isApiUrl = request.url.startsWith('http:://localhost:3000');
if (isLoggedIn && isApiUrl) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${tokenObj.token}`
}
});
}
return next.handle(request);
}
}
login(email: string, password: string) {
return this.http.post<UserToken>(`http://localhost:3000/users/login`, {email, password})
.pipe(
map(token => {
const userToken: UserToken = token;
localStorage.setItem('user-token', JSON.stringify(userToken));
this.tokenSubject.next(userToken);
return userToken;
})
);
}
logout() {
localStorage.removeItem('user-token');
this.tokenSubject.next(null);
this.router.navigate(['/']);
}
@Component({
selector: 'app-nav-bar',
templateUrl: './nav-bar.component.html',
styleUrls: ['./nav-bar.component.scss']
})
export class NavBarComponent implements OnInit {
public isLogged: boolean;
constructor(
private userService: UserService
) {
this.isLogged = this.userService.tokenValue ? true : false;
}
ngOnInit(): void {
}
logout() {
this.userService.logout();
}
}
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.form.invalid) {
return;
}
this.loading = true;
this.userService.login(this.f.email.value, this.f.password.value)
.pipe(first())
.subscribe(
data => {
this.router.navigate([this.returnUrl]);
},
error => {
this.loading = false;
});
}
public get tokenValue(): UserToken {
return this.tokenSubject.value;
}
export class UserToken {
token: string;
}
@Injectable({
providedIn: 'root'
})
export class UserService {
private tokenSubject: BehaviorSubject<UserToken>;
public token: Observable<UserToken>;
constructor(
private router: Router,
private http: HttpClient
) {
this.tokenSubject = new BehaviorSubject<UserToken>(JSON.parse(localStorage.getItem('user-token')));
this.token = this.tokenSubject.asObservable();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment