Permalink
Browse files

Login using email, password

- Add login, register endpoints in back-end
- Handle login, register, logout using Satellizer
1 parent 602924e commit a727d62661919e5544be5beb2a0d89b6df5c6f32 @nguyenkims committed Dec 6, 2015
Showing with 114 additions and 6 deletions.
  1. +62 −1 app.py
  2. +2 −1 static/bower.json
  3. +2 −0 static/index.html
  4. +39 −2 static/main.js
  5. +6 −1 static/partials/login.tpl.html
  6. +3 −1 static/partials/secret.tpl.html
View
@@ -1,8 +1,69 @@
+import os
import flask
-from flask import Flask
+import jwt
+from datetime import datetime, timedelta
+from flask import Flask, jsonify, request
+from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
+app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
+app.config['TOKEN_SECRET'] = 'very secret'
+
+db = SQLAlchemy(app)
+
+
+class User(db.Model):
+ id = db.Column(db.Integer, primary_key=True)
+ email = db.Column(db.String(100), nullable=False)
+ password = db.Column(db.String(100))
+
+ def token(self):
+ payload = {
+ 'sub': self.id,
+ 'iat': datetime.utcnow(),
+ 'exp': datetime.utcnow() + timedelta(days=14)
+ }
+ token = jwt.encode(payload, app.config['TOKEN_SECRET'])
+ return token.decode('unicode_escape')
+
+
+if os.path.exists('db.sqlite'):
+ os.remove('db.sqlite')
+
+db.create_all()
+
+
+@app.route('/auth/signup', methods=['POST'])
+def signup():
+ data = request.json
+
+ email = data["email"]
+ password = data["password"]
+
+ user = User(email=email, password=password)
+ db.session.add(user)
+ db.session.commit()
+
+ return jsonify(token=user.token())
+
+
+@app.route('/auth/login', methods=['POST'])
+def login():
+ data = request.json
+
+ email = data.get("email")
+ password = data.get("password")
+
+ user = User.query.filter_by(email=email).first()
+ if not user:
+ return jsonify(error="No such user"), 404
+
+ if user.password == password:
+ return jsonify(token=user.token()), 200
+ else:
+ return jsonify(error="Wrong email or password"), 400
+
@app.route('/islive')
def islive():
View
@@ -20,6 +20,7 @@
],
"dependencies": {
"angular": "angularjs#~1.4.8",
- "angular-ui-router": "~0.2.15"
+ "angular-ui-router": "~0.2.15",
+ "satellizer": "~0.13.1"
}
}
View
@@ -14,6 +14,8 @@
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/angular-ui-router/release/angular-ui-router.min.js"></script>
+<script src="bower_components/satellizer/satellizer.min.js"></script>
+
<script src="main.js"></script>
</body>
</html>
View
@@ -1,4 +1,4 @@
-var app = angular.module('DemoApp', ['ui.router']);
+var app = angular.module('DemoApp', ['ui.router', 'satellizer']);
app.config(function ($stateProvider, $urlRouterProvider) {
@@ -10,12 +10,49 @@ app.config(function ($stateProvider, $urlRouterProvider) {
.state('secret', {
url: '/secret',
templateUrl: 'partials/secret.tpl.html',
+ controller: 'SecretCtrl'
})
.state('login', {
url: '/login',
- templateUrl: 'partials/login.tpl.html'
+ templateUrl: 'partials/login.tpl.html',
+ controller: 'LoginSignupCtrl'
});
$urlRouterProvider.otherwise('/home');
+});
+
+
+app.controller('LoginSignupCtrl', function ($scope, $auth, $state) {
+
+ $scope.signUp = function () {
+ $auth
+ .signup({email: $scope.email, password: $scope.password})
+ .then(function (response) {
+ $auth.setToken(response);
+ $state.go('secret');
+ })
+ .catch(function (response) {
+ console.log("error response", response);
+ })
+ };
+
+ $scope.login = function () {
+ $auth
+ .login({email: $scope.email, password: $scope.password})
+ .then(function (response) {
+ $auth.setToken(response);
+ $state.go('secret');
+ })
+ .catch(function (response) {
+ console.log("error response", response);
+ })
+ };
+});
+
+app.controller('SecretCtrl', function ($scope, $state, $auth) {
+ $scope.logout = function () {
+ $auth.logout();
+ $state.go("home");
+ };
});
@@ -1 +1,6 @@
-Login
+Login
+
+<input type="text" ng-model="email" placeholder="Email">
+<input type="password" ng-model="password" placeholder="Password">
+<button ng-click="signUp()">Sign up</button>
+<button ng-click="login()">Login</button>
@@ -1 +1,3 @@
-Secret
+Secret
+
+<button ng-click="logout()">Log out</button>

0 comments on commit a727d62

Please sign in to comment.