Skip to content

Commit f593552

Browse files
committed
commit
1 parent 531768d commit f593552

File tree

8 files changed

+313
-35
lines changed

8 files changed

+313
-35
lines changed

__pycache__/crypto.cpython-38.pyc

864 Bytes
Binary file not shown.
1.02 KB
Binary file not shown.

__pycache__/tokens.cpython-38.pyc

860 Bytes
Binary file not shown.

app.py

Lines changed: 105 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1-
from flask import Flask, render_template, request, redirect, session, url_for, flash, jsonify
1+
import cv2
2+
import crypto
3+
from flask import Flask, Response, render_template, request, redirect, session, url_for, flash, jsonify
24
from flask_mail import Mail, Message
35
from werkzeug.utils import secure_filename
4-
from facedetector import faceencodingvalues
5-
from flask_recaptcha import ReCaptcha
6+
from facedetector import faceencodingvalues, predata, detect
7+
import tokens
68
import db
79
import os
810

@@ -13,31 +15,16 @@
1315
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
1416
app.secret_key = os.getenv('SECRET_KEY')
1517

16-
recaptcha = ReCaptcha(app=app)
1718

18-
app.config.update(dict(
19-
RECAPTCHA_ENABLED = True,
20-
RECAPTCHA_SITE_KEY = os.getenv('RECAPTCHA_SITE_KEY'),
21-
RECAPTCHA_SECRET_KEY = os.getenv('RECAPTCHA_SECRET_KEY'),
22-
RECAPTCHA_SIZE = 'invisible',
23-
RECAPTCHA_THEME = "dark",
24-
))
25-
26-
# RECAPTCHA_DATA_ATTRS = {'bind': 'recaptcha-submit', 'callback': 'onSubmitCallback', 'size': 'invisible'}
19+
dbconnect = db.connect()
2720

28-
recaptcha = ReCaptcha()
29-
recaptcha.init_app(app)
3021

31-
32-
dbconnect = db.connect()
22+
global recorded,cap
23+
recorded = "NO"
3324

3425
# =============================================================================================================
3526

36-
def mailing(tomail,username,token,no):
37-
if no == 1:
38-
x,y = "conformation Email","confirm_email"
39-
elif no == 2:
40-
x,y = "reset password","reset_password"
27+
def mailing(tomail,username,token):
4128
try:
4229
app.config['MAIL_SERVER']='smtp.gmail.com'
4330
app.config['MAIL_PORT'] = 465
@@ -48,14 +35,14 @@ def mailing(tomail,username,token,no):
4835
mail = Mail(app)
4936
msg = Message('Hello', sender = os.getenv('EMAIL'), recipients = [tomail])
5037
msg.body = "<h1>Hello Flask message sent from Flask-Mail</h1>"
51-
msg.subject = x
52-
link = "https://adist.herokuapp.com/{}/{}".format(y,token)
53-
msg.html = "<div><h1>change password</h1><h1><a href='"+link+"'}>click me</a></h1></div>"
38+
msg.subject = "Login to your account"
39+
link = "http://127.0.0.1:8000/logincheck/{}".format(token)
40+
msg.html = "<div><h1>Login to your account</h1><h1><a href='"+link+"'}>click here</a></h1></div>"
5441
msg.html = '''<div
5542
style="text-align:center;max-width:600px;background:rgba( 255, 255, 255, 0.25 );box-shadow: 0 8px 32px 0 rgba( 31, 38, 135, 0.37 );backdrop-filter: blur( 4px );border-radius: 10px;border: 1px solid rgba( 255, 255, 255, 0.18 );">
56-
<h1>Adist</h1>
57-
<h2>Verification mail</h2>
58-
<h2>hi {} click the link below to conform your mail</h2>
43+
<h1>Authenticator</h1>
44+
<h2>Login to your account</h2>
45+
<h2>hi {} click the link below to Login to your account</h2>
5946
<h3><a href='{}' >Click Here</a></h3>
6047
<p>Copy paste in browser if the above link is not working: {}</p>
6148
</div>'''.format(username,link,link)
@@ -70,7 +57,10 @@ def mailing(tomail,username,token,no):
7057
@app.route("/home")
7158
def home():
7259
if "user" in session:
73-
return render_template("index.html",user=session["user"])
60+
if "verify" in session:
61+
return render_template("index.html", user = session["user"])
62+
else:
63+
return render_template("verify.html", user = session["user"])
7464
elif "admin" in session:
7565
return redirect(url_for("admin"))
7666
else:
@@ -83,18 +73,69 @@ def login():
8373
return render_template("login.html",RECAPTCHA_SITE_KEY = os.getenv('RECAPTCHA_SITE_KEY'))
8474
if request.method == "POST":
8575
email = request.form.to_dict()["email"]
86-
q = "select * from tempusers where email = '{}'".format(email)
76+
q = "select username,email from tempusers where email = '{}'".format(email)
8777
result = db.select(q)
8878
if len(result) == 0:
8979
flash("Invalid email")
9080
return redirect(url_for("login"))
9181
elif len(result) == 1:
9282
result = result[0]
93-
session["user"] = email
94-
return redirect(url_for("home"))
83+
username,email = result[0],result[1]
84+
85+
token = tokens.generate_confirmation_token(email)
86+
q = "update tempusers set token = '{}' where email = '{}'".format(token,email)
87+
if db.insert(q):
88+
if mailing(email,username,token):
89+
flash("Check your email to for login link")
90+
return redirect(url_for("login"))
91+
else:
92+
flash("Something went wrong during mailing")
93+
return redirect(url_for("login"))
94+
else:
95+
flash("Something went wrong with our database")
96+
return redirect(url_for("login"))
97+
98+
return redirect(url_for("login"))
99+
else:
100+
flash("Something went wrong")
101+
return redirect(url_for("login"))
102+
103+
# ============================================================================================================
104+
105+
@app.route("/logincheck/<token>")
106+
def logincheck(token):
107+
email = tokens.confirm_token(token)
108+
if email == "The token has expired":
109+
flash("The token has expired")
110+
return redirect(url_for("login"))
111+
elif email == "the token is invalid":
112+
flash("the token is invalid")
113+
return redirect(url_for("login"))
114+
elif email:
115+
q = "select username,email,token from tempusers where email = '{}'".format(email)
116+
result = db.select(q)
117+
if len(result) == 1:
118+
result = result[0]
119+
username,email = result[0],result[1]
120+
if token == result[2]:
121+
q = "update tempusers set token = 'no' where email = '{}'".format(email)
122+
if db.insert(q):
123+
session["user"] = email
124+
return redirect(url_for("home"))
125+
126+
else:
127+
flash("Something went wrong with our database")
128+
return redirect(url_for("login"))
129+
else:
130+
flash("use the link that was last sent to your email")
131+
return redirect(url_for("login"))
95132
else:
96133
flash("Something went wrong")
97134
return redirect(url_for("login"))
135+
else:
136+
flash("Something went wrong")
137+
return redirect(url_for("login"))
138+
98139

99140
# ============================================================================================================
100141

@@ -135,7 +176,7 @@ def admin():
135176
if len(facelocs)==0:
136177
flash("No face detected")
137178
return redirect(url_for("admin"))
138-
q = "insert into tempusers(username,email,token,encodings) values('{}','{}','{}','{}')".format(username,email,"no",str(faceencodings.tolist()))
179+
q = "insert into tempusers(username,email,token,encodings) values('{}','{}','{}','{}')".format(username,email,"no",crypto.encryption(str(faceencodings.tolist())))
139180
db.insert(q)
140181
flash("User added")
141182
return redirect(url_for("admin"))
@@ -153,6 +194,35 @@ def admin():
153194
return redirect(url_for("admin"))
154195

155196

197+
# ============================================================================================================
198+
199+
cap = cv2.VideoCapture(0)
200+
# =============================for attendence recording============================================================================================
201+
def gen_frames(email):
202+
global recorded,cap
203+
cap = cv2.VideoCapture(0)
204+
while True:
205+
sucess,img = cap.read()
206+
(frame,ans) = detect(img,email)
207+
recorded = ans
208+
if recorded == "YES":
209+
break
210+
211+
yield(b'--frame\r\n'
212+
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
213+
print("yield condition exit")
214+
cap.release()
215+
216+
217+
218+
@app.route("/video_feed")
219+
def video_feed():
220+
predata(session["user"])
221+
return Response(gen_frames(session["user"]),
222+
mimetype='multipart/x-mixed-replace; boundary=frame')
223+
224+
225+
156226
# ============================================================================================================
157227

158228
@app.route("/logout")
@@ -162,7 +232,8 @@ def logout():
162232

163233
@app.errorhandler(404)
164234
def page_not_found(e):
165-
return redirect("/")
235+
flash("Page not found")
236+
return redirect("/")
166237

167238

168239
if __name__ == '__main__':

crypto.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from Crypto.Cipher import AES
2+
from Crypto.Util.Padding import pad, unpad
3+
from Crypto.Random import get_random_bytes
4+
5+
key = b'\xbc\x96(WA\x82\n\xfbh\x80\xcb\xb2<\x1d\xfea'
6+
iv = b"\xef\xd1\xf4G'T\xb8\x10\xa3w<L\x08\xa0;\x96"
7+
8+
def encryption(plaintext):
9+
plaintext = bytes(plaintext, 'utf-8')
10+
cipher = AES.new(key,AES.MODE_CBC,iv)
11+
text = cipher.encrypt(pad(plaintext,16))
12+
return text.hex()
13+
14+
def decryption(ciphertext):
15+
ciphertext = bytes.fromhex(ciphertext)
16+
decipher = AES.new(key,AES.MODE_CBC,iv)
17+
text = unpad(decipher.decrypt(ciphertext),block_size=16)
18+
return text.decode('utf-8')
19+
20+
# text = 'sasank world'
21+
22+
# encrypted = encryption(text)
23+
# print(encrypted)
24+
25+
# decrypted = decryption(encrypted)
26+
# print(decrypted)

facedetector.py

Lines changed: 76 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,16 @@
1+
from base64 import encode
12
import face_recognition
23
import numpy as np
34
import cv2
5+
import db
6+
import crypto
7+
8+
dbconnect = db.connect()
9+
10+
global knownencodings,count,sub
11+
knownencodings =[]
12+
count = 0
13+
sub=""
414

515
def faceencodingvalues(img):
616
print("===============start=====================================================")
@@ -16,4 +26,69 @@ def faceencodingvalues(img):
1626
print("==================encodeimg==================================================")
1727
# print(encodeimg)
1828

19-
return (encodeimg,faceloc)
29+
return (encodeimg,faceloc)
30+
31+
32+
33+
def predata(email):
34+
encodinglist = []
35+
emaillist = []
36+
q = "select email,encodings from tempusers"
37+
result = db.select(q)
38+
for i in result:
39+
emaillist.append(i[0])
40+
arr = crypto.decryption(i[1])
41+
arr = np.array(eval(arr))
42+
encodinglist.append(arr)
43+
global knownencodings,count
44+
knownencodings = encodinglist
45+
count = emaillist.index(email)
46+
47+
48+
def detect(img,email):
49+
imgS = cv2.resize(img,(0,0),None,0.25,0.25)
50+
imgS = cv2.cvtColor(imgS,cv2.COLOR_BGR2RGB)
51+
facesS = face_recognition.face_locations(imgS)
52+
encodeS = face_recognition.face_encodings(imgS,facesS)
53+
54+
for encodeFace,faceLoc in zip(encodeS,facesS):
55+
matches = face_recognition.compare_faces(knownencodings,encodeFace)
56+
faceDis = face_recognition.face_distance(knownencodings,encodeFace)
57+
matchindex = np.argmin(faceDis)
58+
print("=======matchindex========================================")
59+
print(matchindex)
60+
print(count)
61+
62+
63+
64+
65+
# print("===============start=====================================================")
66+
# imgload = face_recognition.load_image_file(img)
67+
# imgload = cv2.cvtColor(imgload,cv2.COLOR_BGR2RGB)
68+
# try:
69+
# faceloc = face_recognition.face_locations(imgload)[0] # (260, 825, 528, 557)
70+
# except:
71+
# return (img, "NO")
72+
# encodeimg = face_recognition.face_encodings(imgload)[0]
73+
# print("===============faceloc=====================================================")
74+
# # print(faceloc)
75+
# print("==================encodeimg==================================================")
76+
# # print(encodeimg)
77+
# global knownencodings,count,sub
78+
# distances = face_recognition.face_distance(knownencodings,encodeimg)
79+
# print("===============distances=====================================================")
80+
# # print(distances)
81+
# if len(distances) == 0:
82+
# return (img, "NO")
83+
# else:
84+
# distances = np.array(distances)
85+
# min_value = np.min(distances)
86+
# index = np.argmin(distances)
87+
# # print(index)
88+
# if min_value < 0.6:
89+
# if email == emaillist[index]:
90+
# return (img, "YES")
91+
# else:
92+
# return (img, "NO")
93+
# else:
94+
# return (img, "NO")

temp.html

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<!-- <div class="jumbotron text-center">
2+
<div class="container">
3+
<h1>{{ subjectname }}</h1>
4+
<div>
5+
<img src="{{ url_for('video_feed') }}" height="60%">
6+
</div>
7+
<div>
8+
<h1 id="test">not yet recorded</h1>
9+
</div>
10+
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
11+
<script>
12+
$(document).ready(function () {
13+
refresh();
14+
});
15+
16+
function refresh() {
17+
setTimeout(function () {
18+
$.getJSON('/recorded', function (data) {
19+
if (data == "YES") {
20+
window.location.href = "http://127.0.0.1:7890/recorddone";
21+
}
22+
$('#test').text(data);
23+
});
24+
refresh();
25+
}, 1000);
26+
}
27+
</script>
28+
<hr>
29+
30+
31+
</div>
32+
</div> -->

0 commit comments

Comments
 (0)