Commit 89274bdb authored by W.D.R.P. Sandeepa's avatar W.D.R.P. Sandeepa

Merge branch 'it18218640' into 'master'

complete login fun

See merge request !141
parents 2294ffe2 a1c15a36
import re
import MySQLdb
import mysql
from flask import Flask, redirect, url_for, render_template, request, jsonify, make_response
import random
import os
......@@ -18,35 +22,36 @@ app = Flask(__name__)
def home():
return render_template('home.html')
# @app.route('/register', methods =['POST'])
# def register():
# msg = ''
# if request.method == 'POST' and 'username' in request.form and 'password' in request.form and 'email' in request.form:
# username = request.form['username']
# password = request.form['password']
# email = request.form['email']
# cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
# cursor.execute('SELECT * FROM user WHERE name = % s', (username,))
# account = cursor.fetchone()
# if account:
# msg = 'Account already exists !'
# elif not re.match(r'[^@]+@[^@]+\.[^@]+', email):
# msg = 'Invalid email address !'
# elif not re.match(r'[A-Za-z0-9]+', username):
# msg = 'Username must contain only characters and numbers !'
# elif not username or not password or not email:
# msg = 'Please fill out the form !'
# else:
# cursor.execute('INSERT INTO accounts VALUES (NULL, % s, % s, % s)', (username, password, email,))
# mysql.connection.commit()
# msg = 'You have successfully registered !'
# elif request.method == 'POST':
# msg = 'Please fill out the form !'
# return msg
@app.route('/register', methods =['POST'])
def register():
msg = ''
if request.method == 'POST' and 'username' in request.form and 'password' in request.form and 'email' in request.form:
username = request.form['username']
password = request.form['password']
email = request.form['email']
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM user WHERE name = % s', (username,))
account = cursor.fetchone()
if account:
msg = 'Account already exists !'
elif not re.match(r'[^@]+@[^@]+\.[^@]+', email):
msg = 'Invalid email address !'
elif not re.match(r'[A-Za-z0-9]+', username):
msg = 'Username must contain only characters and numbers !'
elif not username or not password or not email:
msg = 'Please fill out the form !'
else:
cursor.execute('INSERT INTO accounts VALUES (NULL, % s, % s, % s)', (username, password, email,))
mysql.connection.commit()
msg = 'You have successfully registered !'
elif request.method == 'POST':
msg = 'Please fill out the form !'
return msg
# Color Function Route (IT18218640)
# Get Color activities route
@app.route("/getColorActivities1")
def getColorActivities1():
return get_color_activities1()
......@@ -60,43 +65,61 @@ def getColorActivitiesResult():
# print("data_dic")
return get_color_activity_result()
# @app.route("/predict", methods=["POST"])
# def predict():
# # get audio file and save it
# audio_file = request.files["file"]
#
# print(f"{request.files['file']}")
# # print(f"{request.files['name']}")
#
# ######################################
# print(f"{request.form['name']}")
# #####################################
# # print(f"{request.json}")
#
# file_name = str(random.randint(0, 100000))
# # audio_file.save((file_name))
#
# # get file name
# # predict_file_name = audio_file.filename
# # predict_file_name = predict_file_name.split("/")
# # new_predict_file_name = predict_file_name[1]
# # new_predict_file_name = new_predict_file_name.split(".")
# # FPFN = new_predict_file_name[0]
# # print(f"{FPFN}")
#
# # invoke keyword spotting service
# kss = Keyword_Spotting_service()
#
# # make a prediction
# predicted_keyword = kss.predict(file_name, request.form['name'])
#
# # remove the audio file
# os.remove(file_name)
#
# # send back the predicted keword in json format
# data = {"Keyword": predicted_keyword}
# return jsonify(data)
# # return "audio_file"
@app.route("/predict", methods=["POST"])
def predict():
data = request.get_json()
print((f"{data}"))
fileitem = data['uri']
# if fileitem.filename:
# # strip the leading path from the file name
fn = os.path.basename(fileitem)
#
# # open read and write the file into the server
open(fn, 'wb').write(fileitem.file.read())
resp = make_response(request.get_json())
resp.headers['Access-Control-Allow-Origin'] = '*'
resp.headers['Content-Type'] = 'application/json'
return resp
# get audio file and save it
# audio_file = request.files["file"]
# audio_file = request.files["name"]
# print((f"{request.data}"))
# print((f"{request.form}"))
# print((f"{request.values}"))
# print((f"{request.json}"))
# print(f"{request.form['name']}")
# file_name = str(random.randint(0, 100000))
# audio_file.save((file_name))
#
# # get file name
# predict_file_name = audio_file.filename
# predict_file_name = predict_file_name.split("/")
# new_predict_file_name = predict_file_name[1]
# new_predict_file_name = new_predict_file_name.split(".")
# FPFN = new_predict_file_name[0]
# # print(f"{FPFN}")
#
# # invoke keyword spotting service
# kss = Keyword_Spotting_service()
#
#
# # make a prediction
# predicted_keyword = kss.predict(file_name, FPFN)
#
# # remove the audio file
# os.remove(file_name)
#
# # send back the predicted keword in json format
# data = {"Keyword" : predicted_keyword}
# return jsonify("print")
# return "Print"
# Read Function Route (IT)
......@@ -119,26 +142,29 @@ def abc():
# Loging
@app.route("/login", methods=['POST'])
def login():
req = request.get_json()
username = req['username']
email = req['email']
password = req['password']
user = getStudentByName(username, password)
user = getStudentByName(email, password)
if len(user) == 0:
data = {
"body": [],
"message": "Failed"
"message": "Failed",
"status": 404
}
else:
data = {
"body": user,
"message": "Success"
"message": "Success",
"status": 200
}
body = jsonify(data)
return make_response(body)
if __name__ == "__main__":
# app.run(host='192.168.8.101')
app.run(host='192.168.8.102')
# app.run(host='192.168.8.100,port='5000', debug=True)
app.run(debug=True)
\ No newline at end of file
# app.run(debug=True)
\ No newline at end of file
......@@ -12,7 +12,7 @@ def create_con():
database="helply",
host="127.0.0.1",
user="root",
password="12345678"
password="rp19970520"
)
return db
......
from API.db.dbConnection import get_data
def getStudentByName(username, password):
qry = 'SELECT * FROM `user` WHERE name = "{}" AND password = "{}"'.format(username, password)
def getStudentByName(email, password):
qry = 'SELECT * FROM `user` WHERE email = "{}" AND password = "{}"'.format(email, password)
user = get_data(qry)
return user
This diff is collapsed.
......@@ -7,7 +7,7 @@ import Home from '../screen/home';
import Start from '../screen/Start';
import Register from '../screen/auth/Register';
import Login from '../screen/auth/Login';
import Splash from '../screen/splash/splash';
import Splash from '../screen/splash/Splash';
import Color from '../screen/Color';
import Blue from '../screen/activity/Blue';
import Read from '../screen/Read';
......
......@@ -3,6 +3,8 @@ import Orientation from 'react-native-orientation-locker';
import React, { useState } from "react";
import { SafeAreaView, ScrollView, View, StyleSheet, ImageBackground, Text, TextInput, TouchableOpacity, Image } from "react-native";
import client from "../client/Client";
const isValidObjectField = (obj) => {
return Object.values(obj).every(value => value.trim());
}
......@@ -66,11 +68,45 @@ const Login = () => {
const submitForm = () => {
if (isValidForm()){
()=> { navigation.navigate("Start")}
console.log(userInfo);
loginFun(userInfo)
}
}
const loginFun = () => {
var formData = JSON.stringify(userInfo);
client.post('login', formData, {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
})
.then((response) => {
console.log(response.data);
if(response.data.status == 404){
return updateError('Please register our system', setError);
}
if(response.data.status == 200){
return navigation.navigate("Start");
}
})
.catch((err) => {
console.log(err);
});
}
return(
<SafeAreaView>
<ScrollView>
......@@ -85,15 +121,15 @@ const Login = () => {
{error ? (<Text style={{color: 'red', fontSize: 18, textAlign: 'center'}}>{error}</Text>) : null}
<View style={styles.form_input}>
<TextInput value={email} autoCapitalize="none" onChangeText={value => handleOnChangeText(value, 'email')} style={styles.text_input} placeholder="Enter Email"></TextInput>
<TextInput id="email" value={email} autoCapitalize="none" onChangeText={value => handleOnChangeText(value, 'email')} style={styles.text_input} placeholder="Enter Email"></TextInput>
</View>
<View style={styles.form_input}>
<TextInput value={password} autoCapitalize="none" secureTextEntry onChangeText={value => handleOnChangeText(value, 'password')} keyboardType="visible-password" style={styles.text_input} placeholder="Enter Password"></TextInput>
<TextInput id="password" value={password} autoCapitalize="none" secureTextEntry onChangeText={value => handleOnChangeText(value, 'password')} style={styles.text_input} placeholder="Enter Password"></TextInput>
</View>
<View style={styles.form_input}>
<TouchableOpacity onPress={()=> { navigation.navigate("Home")}} style={styles.btn}>
<TouchableOpacity onPress={ submitForm } style={styles.btn}>
<Text style={styles.btn_text}>
Sign In
</Text>
......
......@@ -82,11 +82,34 @@ const Register = () => {
const submitForm = () => {
if (isValidForm()){
console.log(userInfo);
// console.log(userInfo);
registerFun(userInfo);
}
}
// import client from "../client/Client";
const registerFun = ()=> {
console.log(userInfo.email);
// client.get('register', userInfo, {
// headers: {
// Accept: 'application/json',
// 'Content-Type': 'application/json',
// },
// })
// .then((response) => {
// console.log(response);
// })
// .catch((err) => {
// console.log(err);
// });
}
return (
<SafeAreaView>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment