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

78 lines
2.2 KiB
TypeScript
Raw Normal View History

///<reference path="../../../browser.d.ts"/>
2016-03-13 18:28:29 +08:00
2016-05-09 23:04:56 +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";
2016-05-09 23:04:56 +08:00
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
2016-05-09 23:04:56 +08:00
declare module ServerInject {
export var user;
}
2016-03-13 18:28:29 +08:00
@Injectable()
2016-05-09 23:04:56 +08:00
export class AuthenticationService {
2016-03-13 18:28:29 +08:00
private _user:User = null;
2016-05-17 05:15:03 +08:00
public OnUserChanged:Event<User>;
2016-03-13 18:28:29 +08:00
2016-05-09 23:04:56 +08:00
constructor(private _userService:UserService) {
2016-05-17 05:15:03 +08:00
this.OnUserChanged = new Event();
//picking up session..
2016-05-26 15:44:13 +08:00
if (this.isAuthenticated() == false && Cookie.get('pigallery2-session') != null) {
2016-05-09 23:04:56 +08:00
if (typeof ServerInject !== "undefined" && typeof ServerInject.user !== "undefined") {
console.log("user found");
this.setUser(ServerInject.user);
}
2016-05-09 23:04:56 +08:00
this.getSessionUser();
}
2016-05-09 23:04:56 +08:00
}
2016-05-09 23:04:56 +08:00
private getSessionUser() {
this._userService.getSessionUser().then((message:Message<User>) => {
if (message.error) {
console.log(message.error);
2016-05-09 23:04:56 +08:00
} else {
this._user = message.result;
2016-05-17 05:15:03 +08:00
this.OnUserChanged.trigger(this._user);
}
});
2016-03-13 18:28:29 +08:00
}
2016-05-09 23:04:56 +08:00
private setUser(user:User) {
2016-05-05 04:20:54 +08:00
this._user = user;
2016-05-17 05:15:03 +08:00
this.OnUserChanged.trigger(this._user);
2016-05-05 04:20:54 +08:00
}
public login(credential:LoginCredential) {
2016-05-09 23:04:56 +08: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-05 04:20:54 +08:00
2016-03-13 18:28:29 +08:00
2016-05-09 23:04:56 +08:00
public isAuthenticated():boolean {
return (this._user && this._user != null) ? true : false;
2016-03-13 18:28:29 +08:00
}
2016-05-09 23:04:56 +08:00
public getUser() {
return this._user;
}
2016-03-13 18:28:29 +08:00
2016-05-17 05:15:03 +08:00
public logout() {
this._userService.logout();
this.setUser(null);
}
2016-03-13 18:28:29 +08:00
}