diff --git a/src/auth/auth-service.js b/src/auth/auth-service.js new file mode 100644 index 00000000..011f633e --- /dev/null +++ b/src/auth/auth-service.js @@ -0,0 +1,47 @@ +import axios from "axios"; + +export const loginIn = body => { + return axios.post("http://donut-api-prod.codeuino.org/auth/login", { + email: body.email, + password: body.password + }); +}; + +export const decodeResponse = response => { + const parts = response.split("."); + if (parts.length !== 3) { + throw new Error( + "Auth token must have 3 parts; " + parts.length + " provided." + ); + } + return { + header: JSON.parse(_base64UrlDecode(parts[0])), + payload: JSON.parse(_base64UrlDecode(parts[1])), + signature: _base64UrlDecode(parts[2]) + }; +}; + +function _base64UrlDecode(base64UrlString) { + var base64String = base64UrlString + .replace(/-/g, "+") // replace character 62 + .replace(/_/g, "/"); // replace character 63 + + switch (base64String.length % 4) { + case 0: { + break; + } + case 2: { + base64String += "=="; + break; + } + case 3: { + base64String += "="; + break; + } + default: { + throw new Error("Illegal base64url string."); + } + } + + return window.atob(base64String); +} diff --git a/src/auth/login-form/login-form.js b/src/auth/login-form/login-form.js index 127299c1..21b6178b 100644 --- a/src/auth/login-form/login-form.js +++ b/src/auth/login-form/login-form.js @@ -1,15 +1,68 @@ import React, { Component } from "react"; import { Form, Button } from "react-bootstrap"; import "./login-form.scss"; +import cookie from "react-cookies"; +import { withRouter } from "react-router-dom"; +import * as auth from "../auth-service"; class LoginForm extends Component { + constructor(props) { + super(props); + this.state = { + email: "", + password: "" + }; + } + + handleChange = (event, params) => { + event.preventDefault(); + params === "email" + ? this.setState({ email: event.target.value }) + : this.setState({ password: event.target.value }); + }; + + checkValidation = () => { + if (this.state.email.includes("@") && this.state.email.includes(".")) { + return true; + } + return false; + }; + + authorizeUser = event => { + event.preventDefault(); + const isValidated = this.checkValidation(); + if (isValidated) { + auth + .loginIn(this.state) + .then(response => { + const decodedToken = auth.decodeResponse(response.data.token); + this.setSession(decodedToken); + }) + .catch(error => { + console.log(error); + }); + } + }; + + setSession = token => { + const id = token.payload._id; + cookie.save("userId", id, { path: "/" }); + this.props.history.push("/dashboard"); + }; + render() { return (