Last active
November 6, 2017 13:39
-
-
Save max2320/b801f0b9042d341692441db34951dda2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Connector from './connector'; | |
export default class Api{ | |
constructor(){ | |
this.connector = new Connector(); | |
} | |
all(onSuccess,onError){ | |
this.connector.get(`${this.url}`) | |
.success(onSuccess).fail(onError); | |
} | |
one(id, onSuccess,onError){ | |
this.connector.get(`${this.url}/${id}`) | |
.success(onSuccess).fail(onError); | |
} | |
create(data, onSuccess,onError){ | |
this.connector.post(`${this.url}`, data) | |
.success(onSuccess).fail(onError); | |
} | |
update(data, id, onSuccess,onError){ | |
this.connector.patch(`${this.url}/${id}`, data) | |
.success(onSuccess).fail(onError); | |
} | |
enable(id, onSuccess,onError){ | |
this.connector.get(`${this.url}/${id}/enable`) | |
.success(onSuccess).fail(onError); | |
} | |
disable(id, onSuccess,onError){ | |
this.connector.get(`${this.url}/${id}/disable`) | |
.success(onSuccess).fail(onError); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Api from './api'; | |
export default class Auth extends Api{ | |
authenticate(data, onSuccess, onError){ | |
this.connector.post("/auth/sign_in", data) | |
.success(onSuccess).fail(onError); | |
} | |
requestPasswordRecover(data, onSuccess, onError){ | |
this.connector.post("/auth/password", data) | |
.success(onSuccess).fail(onError); | |
} | |
verifyToken(onSuccess, onError){ | |
this.connector.get("/auth/validate_token") | |
.success(onSuccess).fail(onError); | |
} | |
passwordUpdate(data, onSuccess, onError, provisionedSession){ | |
this.connector.put("/auth/password", data, provisionedSession) | |
.success(onSuccess).fail(onError); | |
} | |
logout(onSuccess, onError){ | |
this.connector.delete("/auth/sign_out") | |
.success(onSuccess).fail(onError); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import _ from 'lodash'; | |
import {decode, encode} from 'querystring'; | |
import Promise from 'promise-polyfill'; | |
import fetchPonyfill from 'fetch-ponyfill'; | |
if (!window.Promise) { | |
window.Promise = Promise; | |
} | |
const {fetch, Request, Response, Headers} = fetchPonyfill(); | |
export default class Connector{ | |
constructor(){ | |
this.data = {} | |
this.apiURL = '/api'; | |
this.defaultHeader = { | |
'Accept': 'application/json', | |
}; | |
this.allowedSuccess = [200, 201, 304]; | |
this.hasError = false; | |
} | |
setData(data){ | |
this.data = data; | |
} | |
buildURL(url){ | |
return `${this.apiURL}${url}`; | |
} | |
buildheader(headers){ | |
return _.merge(this.defaultHeader, window.session.applySessionHeader(headers)); | |
} | |
buildRequest(url, method, headers = {}){ | |
var params = { | |
method: method, | |
headers: this.buildheader(headers) | |
}; | |
if(method == 'POST' || method == 'PATCH' || method == 'PUT'){ | |
params['body']= encode(this.data); | |
} | |
return new Request(this.buildURL(url), params); | |
} | |
formHeader(){ | |
return { | |
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" | |
}; | |
} | |
post(url, data, customHeaders = {}){ | |
this.setData(data); | |
return this.doRequest(this.buildRequest(url, 'POST', _.merge(customHeaders, this.formHeader()) )); | |
} | |
put(url, data, customHeaders = {}){ | |
this.setData(data); | |
return this.doRequest(this.buildRequest(url, 'PUT', _.merge(customHeaders, this.formHeader()) )); | |
} | |
patch(url, data, customHeaders = {}){ | |
this.setData(data); | |
return this.doRequest(this.buildRequest(url, 'PATCH', _.merge(customHeaders, this.formHeader()) )); | |
} | |
get(url, customHeaders = {}){ | |
return this.doRequest(this.buildRequest(url,'GET',{ | |
'Accept': 'application/json', | |
})); | |
} | |
delete(url, customHeaders = {}){ | |
return this.doRequest(this.buildRequest(url,'DELETE',{ | |
'Accept': 'application/json', | |
})); | |
} | |
success(callback){ | |
if(callback){ | |
this.handleSuccess = callback; | |
} | |
return this; | |
} | |
fail(callback){ | |
if(callback){ | |
this.handleError = callback; | |
} | |
return this; | |
} | |
setStatus(status){ | |
if(this.allowedSuccess.indexOf(status) == -1){ | |
this.hasError = true; | |
} | |
} | |
doRequest(request){ | |
this.hasError = false; | |
fetch(request).then((response) =>{ | |
this.updateHeaders(response); | |
this.setStatus(response.status); | |
return response.json(); | |
}).then((json) =>{ | |
if(this.hasError){ | |
if(this.handleError){ | |
this.handleError(json); | |
} | |
}else{ | |
if(this.handleSuccess){ | |
this.handleSuccess(json); | |
} | |
} | |
}).catch((error) =>{ | |
console.error(error); | |
}); | |
return this; | |
} | |
updateHeaders(response){ | |
var headers = response.headers; | |
if(headers.get("access-token")){ | |
window.session.updateSession({ | |
"access-token": headers.get("access-token"), | |
"token-type": headers.get("token-type"), | |
"client": headers.get("client"), | |
"expiry": headers.get("expiry"), | |
"uid": headers.get("uid") | |
}); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import _ from 'lodash'; | |
import {encode} from 'querystring'; | |
import Cookies from 'js-cookie'; | |
import Auth from '../api/auth'; | |
export default class Session{ | |
constructor(session){ | |
if(typeof session != 'undefined'){ | |
this.updateSession(session); | |
}else{ | |
this.restoreSession(); | |
} | |
this.sessionPath = '/'; | |
} | |
registerUpdate(){ | |
this.updatedAt = new Date(); | |
} | |
isAuthenticate(){ | |
return this.accessToken != undefined; | |
} | |
isAdmin(){ | |
return this.isAuthenticate() && this.userProfile == 'admin'; | |
} | |
getToken(){ | |
return this.accessToken; | |
} | |
getTokenType(){ | |
return this.accessTokenType; | |
} | |
getClient(){ | |
return this.client; | |
} | |
getExpiry(){ | |
return this.expiry; | |
} | |
getUid(){ | |
return this.uid; | |
} | |
applySessionHeader(headers){ | |
if(this.accessToken){ | |
return _.merge(this.session, headers); | |
}else{ | |
return headers; | |
} | |
} | |
updateSession(session){ | |
this.clearCookies(); | |
this.session = session; | |
this.accessToken = session["access-token"]; | |
this.tokenType = session["token-type"]; | |
this.client = session["client"]; | |
this.expiry = session["expiry"]; | |
this.uid = session["uid"]; | |
this.storeCookies(); | |
this.validateSession(); | |
} | |
validateSession(){ | |
if(this.isAuthenticate() && (typeof this.updatedAt == 'undefined' || this.updatedAt - new Date() > 1500)){ | |
this.registerUpdate(); | |
new Auth().verifyToken((success)=>{ | |
// console.log("Token Verification", success); | |
if(success['success'] == true){ | |
this.registerUpdate(); | |
this.userProfile = success.data.profile; | |
}else{ | |
this.removeCookies(); | |
} | |
}, (error)=>{ | |
if(error['success'] == true){ | |
this.registerUpdate(); | |
this.userProfile = success.data.profile; | |
}else{ | |
this.removeCookies(); | |
} | |
}); | |
} | |
} | |
restoreSession(){ | |
this.accessToken = Cookies.get("access-token", {path: this.sessionPath}); | |
this.tokenType = Cookies.get("token-type", {path: this.sessionPath}); | |
this.client = Cookies.get("client", {path: this.sessionPath}); | |
this.expiry = Cookies.get("expiry", {path: this.sessionPath}); | |
this.uid = Cookies.get("uid", {path: this.sessionPath}); | |
this.session = { | |
"access-token": this.accessToken, | |
"token-type": this.tokenType, | |
"client": this.client, | |
"expiry": this.expiry, | |
"uid": this.uid, | |
}; | |
} | |
storeCookies(){ | |
Cookies.set("access-token", this.accessToken, {path: this.sessionPath}); | |
Cookies.set("token-type", this.tokenType, {path: this.sessionPath}); | |
Cookies.set("client", this.client, {path: this.sessionPath}); | |
Cookies.set("expiry", this.expiry, {path: this.sessionPath}); | |
Cookies.set("uid", this.uid, {path: this.sessionPath}); | |
} | |
clearCookies(){ | |
Cookies.remove("access-token", {path: this.sessionPath}); | |
Cookies.remove("token-type", {path: this.sessionPath}); | |
Cookies.remove("client", {path: this.sessionPath}); | |
Cookies.remove("expiry", {path: this.sessionPath}); | |
Cookies.remove("uid", {path: this.sessionPath}); | |
this.accessToken = undefined; | |
this.tokenType = undefined; | |
this.client = undefined; | |
this.expiry = undefined; | |
this.uid = undefined; | |
this.session = {}; | |
} | |
removeCookies(){ | |
this.clearCookies(); | |
window.location.href = '/'; | |
// window.location.reload(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment