1
0
mirror of https://github.com/xuthus83/pigallery2.git synced 2024-11-03 21:04:03 +08:00
pigallery2/frontend/app/model/network/authentication.service.ts

73 lines
2.1 KiB
TypeScript
Raw Normal View History

///<reference path="../../../browser.d.ts"/>
2016-03-13 18:28:29 +08:00
2016-05-04 23:20:21 +08: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";
import { Cookie } from 'ng2-cookies/ng2-cookies';
2016-05-05 00:34:54 +08:00
import {ErrorCodes} from "../../../../common/entities/Error";
2016-03-13 18:28:29 +08:00
declare module ServerInject{
export var user;
}
2016-03-13 18:28:29 +08:00
@Injectable()
export class AuthenticationService{
private _user:User = null;
2016-03-13 18:28:29 +08:00
public OnAuthenticated:Event<User>;
constructor(private _userService: UserService){
2016-03-13 18:28:29 +08:00
this.OnAuthenticated = new Event();
//picking up session..
if(this.isAuthenticated() == false && Cookie.getCookie('pigallery2-session') != null){
if(typeof ServerInject !== "undefined" && typeof ServerInject.user !== "undefined"){
console.log("user found");
this.setUser(ServerInject.user);
}
this.getSessionUser();
}
}
private getSessionUser(){
this._userService.getSessionUser().then( (message:Message<User>) =>{
if(message.error){
console.log(message.error);
}else{
this._user = message.result;
this.OnAuthenticated.trigger(this._user);
}
});
2016-03-13 18:28:29 +08:00
}
2016-05-05 04:20:54 +08:00
private setUser(user:User){
this._user = user;
this.OnAuthenticated.trigger(this._user);
}
public login(credential:LoginCredential) {
this._userService.login(credential).then( (message:Message<User>) =>{
if(message.error){
2016-05-05 00:34:54 +08:00
console.log(ErrorCodes[message.error.code] + "message: "+ message.error.message);
}else{
this.setUser(message.result);
}
});
}
2016-05-05 04:20:54 +08:00
2016-03-13 18:28:29 +08:00
public isAuthenticated():boolean{
return (this._user && this._user != null) ? true : false;
2016-03-13 18:28:29 +08:00
}
public getUser(){
return this._user;
}
2016-03-13 18:28:29 +08:00
}