password-setting.service.ts 2.09 KB
Newer Older
1 2 3 4 5 6 7
import { Injectable } from '@angular/core';
import { Headers, Http, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/toPromise';

import { PasswordSetting } from './password-setting';

const passwordChangeEndpoint = "/api/users/:user_id/password";
Steven Zou's avatar
Steven Zou committed
8 9
const sendEmailEndpoint = "/sendEmail";
const resetPasswordEndpoint = "/reset";
10 11 12 13 14 15 16 17 18 19 20 21 22 23

@Injectable()
export class PasswordSettingService {
    private headers: Headers = new Headers({
        "Accept": 'application/json',
        "Content-Type": 'application/json'
    });
    private options: RequestOptions = new RequestOptions({
        'headers': this.headers
    });

    constructor(private http: Http) { }

    changePassword(userId: number, setting: PasswordSetting): Promise<any> {
Steven Zou's avatar
Steven Zou committed
24
        if (!setting || setting.new_password.trim() === "" || setting.old_password.trim() === "") {
25 26 27
            return Promise.reject("Invalid data");
        }

Steven Zou's avatar
Steven Zou committed
28
        let putUrl = passwordChangeEndpoint.replace(":user_id", userId + "");
29
        return this.http.put(putUrl, JSON.stringify(setting), this.options)
Steven Zou's avatar
Steven Zou committed
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
            .toPromise()
            .then(() => null)
            .catch(error => {
                return Promise.reject(error);
            });
    }

    sendResetPasswordMail(email: string): Promise<any> {
        if (!email) {
            return Promise.reject("Invalid email");
        }

        let getUrl = sendEmailEndpoint + "?email=" + email;
        return this.http.get(getUrl, this.options).toPromise()
            .then(response => response)
            .catch(error => {
                return Promise.reject(error);
            })
    }

    resetPassword(uuid: string, newPassword: string): Promise<any> {
        if (!uuid || !newPassword) {
            return Promise.reject("Invalid reset uuid or password");
        }

        return this.http.post(resetPasswordEndpoint, JSON.stringify({
            "reset_uuid": uuid,
            "password": newPassword
        }), this.options)
            .toPromise()
            .then(response => response)
            .catch(error => {
                return Promise.reject(error);
            });
64 65 66
    }

}