Fakultas Ilmu Komputer UI

app.py 6.54 KB
Newer Older
1
import os
2
import requests 
3
import telegram
4
import urllib.parse
5

6
from flask import Flask, request, render_template, jsonify, redirect, url_for
7
from flask_sqlalchemy import SQLAlchemy
zakiraihan's avatar
zakiraihan committed
8
from sso.utils import authenticate, get_cas_client
9
from sso.csui_helper import get_access_token
10
11
12
13
14
15
16

global bot
global TOKEN
TOKEN = os.environ.get('BOT_TOKEN')
bot = telegram.Bot(token=TOKEN)
URL = os.environ.get('URL')

17
app = Flask(__name__)
18
app.config.from_object(os.environ.get('APP_SETTINGS'))
19
20
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
21

22
# ================================================================ Bot Handler ================================================================ #
23
24
@app.route('/{}'.format(TOKEN), methods=['POST'])
def respond():
25
    from navigation.navigation import botNavigation
26
27
    # retrieve the message in JSON and then transform it to Telegram object
    update = telegram.Update.de_json(request.get_json(force=True), bot)
28
    botNavigation(bot, update)
29
30
    return 'ok'

31
32
@app.route('/setwebhook', methods=['GET', 'POST'])
def set_webhook():
33
34
    # we use the bot object to link the bot to our app which live
    # in the link provided by URL
35
    s = bot.setWebhook('{URL}{HOOK}'.format(URL=("https://" + URL + '/'), HOOK=TOKEN))
36
37
38
39
40
    # something to let us know things work
    if s:
        return "webhook setup ok"
    else:
        return "webhook setup failed"
41

42
43
# ============================================================================================================================================= #

44
45
46
47
@app.route('/')
def hello():
    return "Hello World!"

zakiraihan's avatar
zakiraihan committed
48
49
50
51
52
53
54
55
56
57
58
@app.route('/sendNotification/custom', methods=['POST'])
def sendNotifCustom():
    from models.AccountModel import AccountModel
    req_data = request.get_json()
    user = AccountModel.query.filter(AccountModel.ssoId==req_data['username']).first()
    if (user is None):
        return {'status': 404, 'message': 'User not found'}
    elif (user.chatId == None):
        return {'status': 500, 'message': 'User notification is being turned off'}
    else:
        param = urllib.parse.urlencode({'chat_id': user.chatId, 'text': req_data['message']})
59
        url = "https://api.telegram.org/bot" + TOKEN + "/sendMessage?" + param + "&parse_mode=HTML"
zakiraihan's avatar
zakiraihan committed
60
61
62
63
64
        r = requests.get(url = url) 
        return r.json()

@app.route('/sendNotification/sisurat', methods=['POST'])
def sendNotifSisurat():
65
    from models.AccountModel import AccountModel
zakiraihan's avatar
zakiraihan committed
66
    from telebot.sisuratNotif import createNotifSisurat
67
    req_data = request.get_json()
68
    user = AccountModel.query.filter(AccountModel.ssoId==req_data['username']).first()
69
70
    if (user is None):
        return {'status': 404, 'message': 'User not found'}
71
72
73
    elif (user.chatId == None):
        return {'status': 500, 'message': 'User notification is being turned off'}
    else:
zakiraihan's avatar
zakiraihan committed
74
75
        textNotif = createNotifSisurat(req_data)
        param = urllib.parse.urlencode({'chat_id': user.chatId, 'text': textNotif})
zakiraihan's avatar
zakiraihan committed
76
        url = "https://api.telegram.org/bot" + TOKEN + "/sendMessage?" + param + "&parse_mode=HTML"
77
78
        r = requests.get(url = url) 
        return r.json()
79

zakiraihan's avatar
zakiraihan committed
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
@app.route("/auth/", methods=['POST'])
def auth():
    data = request.json
    ticket = data.get("ticket")
    service_url = data.get("service_url")
    if (ticket is not None) and (service_url is not None):
        client = get_cas_client(service_url)
        sso_profile = authenticate(ticket, client)
        if sso_profile is not None:
            user_data = sso_profile
            print(sso_profile)
            return (jsonify(user_data), 200)

    return (jsonify(), 400)

95
96
97
98
99
100
101
102
103
104
105
106
107
108
@app.route('/loginsso', methods=['GET'])
def renderLoginSSOPage():
    return render_template('loginSSO.html')

@app.route('/loginsso/auth', methods=['POST'])
def getLoginSSOData():
    username = request.form['username']
    password = request.form['password']
    try:
        access_token = get_access_token(username, password)
    except Exception as e:
        access_token = None

    if (access_token != None):
zakiraihan's avatar
zakiraihan committed
109
        return redirect(url_for('.renderSetPhoneNumber', username=username))
110
    else:    
zakiraihan's avatar
zakiraihan committed
111
112
113
114
        return redirect(url_for('.renderFailedToLoginSSO'))

@app.route('/loginsso/setPhoneNumber', methods=['GET'])
def renderSetPhoneNumber():
115
    from telebot.utils import check_if_user_exist
zakiraihan's avatar
zakiraihan committed
116
    username = request.args.get('username')
117
118
119
120
    if (check_if_user_exist(username)):
        return render_template('accountExist.html', username=username)
    else:
        return render_template('authPhoneNumber.html', username=username)
zakiraihan's avatar
zakiraihan committed
121
122
123
124
125
126
127

@app.route('/submitPhoneNumber', methods=['POST'])
def createSSOAccount():
    from telebot.utils import create_user_sso_account
    print(request.form)
    username = request.form['username']
    phoneNumber = request.form['phoneNumber']
zakiraihan's avatar
zakiraihan committed
128
129
    createdSSOAccountStatus = create_user_sso_account(username, phoneNumber)
    # createdSSOAccountStatus = "success"
zakiraihan's avatar
zakiraihan committed
130
131
132
    if (createdSSOAccountStatus == "success"):
        return render_template('successToLoginSSO.html', username=username)
    elif (createdSSOAccountStatus == "failed"):
ZAKI RAIHAN's avatar
ZAKI RAIHAN committed
133
        return render_template('failedToLoginSSO.html', username=username)
zakiraihan's avatar
zakiraihan committed
134
135
136
137
138
139
    else:
        return "Error while creating account"

@app.route('/loginsso/failed', methods=['GET'])
def renderFailedToLoginSSO():
    return render_template('failedToLoginSSO.html')
140

141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
@app.route('/logoutsso', methods=['POST'])
def renderLogoutStatus():
    from telebot.utils import logoutSSOUser
    username = request.form['username']
    logoutStatus = logoutSSOUser(username)
    if (logoutStatus == 'success'):
        return render_template('successToLogoutSSO.html', username=username)
    else:
        return render_template('failedToLogoutSSO.html', username=username)

@app.route('/changePhoneNumber', methods=['POST'])
def renderChangePassword():
    from telebot.utils import getAccountCurrentPhoneNumber
    username = request.form['username']
    phoneNumber = getAccountCurrentPhoneNumber(username)
    return render_template('changePhoneNumber.html', username=username, currentPhoneNumber=phoneNumber)

@app.route('/changePhoneNumber/submit', methods=['POST'])
def renderChangePhoneNumberResult():
    from telebot.utils import changeAccountPhoneNumber
    username = request.form['username']
    phoneNumber = request.form['phoneNumber']
    changePhoneNumberStatus = changeAccountPhoneNumber(username, phoneNumber)
    if (changePhoneNumberStatus == 'success'):
        return render_template('successChangePhoneNumber.html', username=username, phoneNumber=phoneNumber)
    else:
        return render_template('failedChangePhoneNumber.html', username=username)


170
if __name__ == '__main__':
171
    app.run(threaded=True)