Browse Source

Adding the login-ex.py and the explanations in the README

SnowCode 5 years ago
parent
commit
cafedbb400
3 changed files with 101 additions and 43 deletions
  1. 10 43
      README.md
  2. BIN
      database.db
  3. 91 0
      login-ex.py

+ 10 - 43
README.md

@@ -53,47 +53,14 @@ In bonus you can also uses the 'login.py' script to speed up the devloppement of
 
 ## How to use the login.py
 
-1. Add login.py file into the root folder of your project
-2. Into your main app file you can add the following snippet:
-
-```python
-# Import the login library
-from login import *
-
-# Create a class User and a variable db containing the database from sqlalchemy
-
-# In the login page back end:
-@app.route('/login')
-def login():
-	try: 
-		loginUser(request.form['username'], request.form['password'], User)
-		return 'You are now logged in. as ' + current_user.username
-	except:
-		return 'Username or password invalid.'
-
-@app.route('/register')
-def register():
-	try:
-		createUser(request.form['username'], request.form['password'], db, User)
-		return 'New account created, you are logged in.'
-	except:
-		return 'An error occurs, probably because this username is already taken.'
-
-@app.route('/logout')
-def logout():
-	logout_user()
-	return 'You are logged out.'
-```
-
-This is the class User:
-
-```python
-class User(UserMixin, db.Model):
-	id = db.Column(db.Integer, primary_key=True)
-	username = db.Column(db.Text, unique=True)
-	password = db.Column(db.Text)
-	def __init__(self, username, password):
-		self.username = username
-		self.password = password
-```
+### Install the requirements
+
+* Flask
+* Flask_sqlalchemy
+* FLask_login
+* Hashlib
+
+### Usage
+
+You can see an example of implementation in the file [login-ex.py](./login-ex.py). 
 

BIN
database.db


+ 91 - 0
login-ex.py

@@ -0,0 +1,91 @@
+# Warning: This app is long, so for your case I recommend you to put the db and the User definition into anotehr file
+# Also I recommend you to use templates, see 'app.py' for more informations.
+
+# Import all the modules
+from flask import Flask, request
+from flask_login import UserMixin
+from flask_sqlalchemy import SQLAlchemy
+from login import *
+
+# Define 'app'
+app = Flask(__name__)
+
+# Define db
+app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
+app.config['SECRET_KEY'] = 'aghzi vnguierhtrutizo hard to guess indeeed'
+db = SQLAlchemy(app)
+
+# Define the User database
+class User(UserMixin, db.Model):
+    id = db.Column(db.Integer, primary_key=True)
+    username = db.Column(db.Text, unique=True)
+    password = db.Column(db.Text)
+    def __init__(self, username, password):
+        self.username = username
+        self.password = password
+db.create_all()
+
+# Create the login manager
+createLoginManager(app, User)
+
+# Define the login page
+@app.route('/login')
+def renderLogin():
+    # Return a form
+    return """
+    <form action='/login/post' method='post'>
+        <p>Username: <input type="text" name="username"></p>
+        <p>Password: <input type="password" name="password"></p>
+        <p><button type="submit">Login</button></p>
+    </form>
+    """
+
+@app.route('/register')
+def renderRegister():
+    # Return a form
+    return """
+        <form action='/register/post' method='post'>
+            <p>Username: <input type="text" name="username"></p>
+            <p>Password: <input type="password" name="password"></p>
+            <p><button type="submit">Register</button></p>
+        </form>
+        """
+@app.route('/login/post', methods=['POST'])
+def login():
+    # Take the values out the form
+    username = request.form['username']
+    password = request.form['password']
+
+    # Try to login, if not, return error
+    try:
+        loginUser(username, password, User)
+        return "You are now logged in as " + current_user.username
+    except:
+        return "Invalid username or password"
+
+@app.route('/register/post', methods=['POST'])
+def register():
+    # Take the value out the form
+    username = request.form['username']
+    password = request.form['password']
+
+    # Try to register, if not return error
+    try:
+        createUser(username, password, db, User)
+        return "New user created you are now logged in as " + current_user.username
+    except:
+        return "This username is already taken: " + username
+
+# Logout the current user
+@app.route('/logout')
+def logout():
+    logout_user()
+
+# Using login_required to make a page private
+@app.route('/locked')
+@login_required
+def locked():
+    return "Hello " + current_user.username + " welcome to your private page."
+
+# Run the app in mode debug
+app.run(debug=True)