1
0
mirror of https://github.com/bpatrik/pigallery2.git synced 2024-12-16 11:37:13 +02:00
pigallery2/frontend/app/model/network/authentication.service.ts

78 lines
2.2 KiB
TypeScript
Raw Normal View History

///<reference path="../../../browser.d.ts"/>
2016-03-13 12:28:29 +02:00
2016-05-09 17:04:56 +02:00
import {Injectable} from "@angular/core";
import {User} from "../../../../common/entities/User";
import {Event} from "../../../../common/event/Event";
import {UserService} from "./user.service.ts";
import {LoginCredential} from "../../../../common/entities/LoginCredential";
import {Message} from "../../../../common/entities/Message";
2016-05-09 17:04:56 +02:00
import {Cookie} from "ng2-cookies/ng2-cookies";
2016-05-04 18:34:54 +02:00
import {ErrorCodes} from "../../../../common/entities/Error";
2016-03-13 12:28:29 +02:00
2016-05-09 17:04:56 +02:00
declare module ServerInject {
export var user;
}
2016-03-13 12:28:29 +02:00
@Injectable()
2016-05-09 17:04:56 +02:00
export class AuthenticationService {
2016-03-13 12:28:29 +02:00
private _user:User = null;
2016-05-16 23:15:03 +02:00
public OnUserChanged:Event<User>;
2016-03-13 12:28:29 +02:00
2016-05-09 17:04:56 +02:00
constructor(private _userService:UserService) {
2016-05-16 23:15:03 +02:00
this.OnUserChanged = new Event();
//picking up session..
2016-05-26 09:44:13 +02:00
if (this.isAuthenticated() == false && Cookie.get('pigallery2-session') != null) {
2016-05-09 17:04:56 +02:00
if (typeof ServerInject !== "undefined" && typeof ServerInject.user !== "undefined") {
console.log("user found");
this.setUser(ServerInject.user);
}
2016-05-09 17:04:56 +02:00
this.getSessionUser();
}
2016-05-09 17:04:56 +02:00
}
2016-05-09 17:04:56 +02:00
private getSessionUser() {
this._userService.getSessionUser().then((message:Message<User>) => {
if (message.error) {
console.log(message.error);
2016-05-09 17:04:56 +02:00
} else {
this._user = message.result;
2016-05-16 23:15:03 +02:00
this.OnUserChanged.trigger(this._user);
}
});
2016-03-13 12:28:29 +02:00
}
2016-05-09 17:04:56 +02:00
private setUser(user:User) {
2016-05-04 22:20:54 +02:00
this._user = user;
2016-05-16 23:15:03 +02:00
this.OnUserChanged.trigger(this._user);
2016-05-04 22:20:54 +02:00
}
public login(credential:LoginCredential) {
2016-05-09 17:04:56 +02:00
this._userService.login(credential).then((message:Message<User>) => {
if (message.error) {
console.log(ErrorCodes[message.error.code] + "message: " + message.error.message);
} else {
this.setUser(message.result);
}
});
}
2016-05-04 22:20:54 +02:00
2016-03-13 12:28:29 +02:00
2016-05-09 17:04:56 +02:00
public isAuthenticated():boolean {
return (this._user && this._user != null) ? true : false;
2016-03-13 12:28:29 +02:00
}
2016-05-09 17:04:56 +02:00
public getUser() {
return this._user;
}
2016-03-13 12:28:29 +02:00
2016-05-16 23:15:03 +02:00
public logout() {
this._userService.logout();
this.setUser(null);
}
2016-03-13 12:28:29 +02:00
}