Skip to content

Commit

Permalink
Temporary fix to accept users without real verification
Browse files Browse the repository at this point in the history
  • Loading branch information
ghrlt committed Sep 25, 2023
1 parent a5cfbba commit f49d6fb
Show file tree
Hide file tree
Showing 5 changed files with 138 additions and 24 deletions.
4 changes: 3 additions & 1 deletion .env
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
APP_NAME="BdeWhi-DiscordBot"
ENV_MODE="prod"
ENV_MODE="dev"

EPSIAPI_USERSURL="https://users.ws.montpellier.epsi.fr/api/users/"
16 changes: 16 additions & 0 deletions apis/wigorservices.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,13 +146,29 @@ def parseClass(self, _class):
classObj.professor = ' '.join(professor)
else:
classObj.professor = 'None'

if isinstance(br.nextSibling, bs4.element.NavigableString):
classObj.classGrade = {
'full': br.nextSibling,
'level': br.nextSibling.split()[0],
'group': br.nextSibling.split()[-1],
'parcours': br.nextSibling.split()[1],
'school': br.nextSibling.split()[2],
'place': br.nextSibling.split()[3],
'year': br.nextSibling.split()[4]
}
else:
classObj.classGrade = {}
else:
classObj.professor = 'You'


if _class.find('td', class_='TCSalle').text == "Salle:Aucune":
classObj.place = ""
classObj.room = ""
elif _class.find('td', class_='TCSalle').text.startswith('Salle:M:'):
classObj.place = "Distanciel"
classObj.room = ""
else:
classObj.place = _class.find('td', class_='TCSalle').text.split('(')[1].strip(')')
classObj.room = _class.find('td', class_='TCSalle').text.split('(')[0].split(':')[1].strip('.')
Expand Down
1 change: 1 addition & 0 deletions env.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ def isItDevEnvironment():
raise ValueError("EPSIAPI_USERSURL is not set.")

ASK_FOR_PASSWORD_ON_JOIN = config.get("ASK_FOR_PASSWORD_ON_JOIN", "False").lower() in ["true", "yes", "y", "1"]
FETCH_USER_DETAILS = config.get("FETCH_USER_DETAILS", "False").lower() in ["true", "yes", "y", "1"]


logger.info("App: %s | Env: %s | Log: %s", APP_NAME, ENVMODE, LOG_LEVEL)
Expand Down
44 changes: 44 additions & 0 deletions slash_commands/admin.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from __main__ import bot, slash
import env
import apis
import utils
import database

import os
import sys
Expand Down Expand Up @@ -106,6 +108,48 @@ async def _setStatus(

await interaction.followup.send(content=msg, ephemeral=True)

@app_commands.command(name="update_users", description="Force all users update")
async def _updateUsers(
self, interaction: discord.Interaction
) -> None:
await interaction.response.defer(ephemeral=True)

for member in interaction.guild.members:

print("Updating %s" % member.name)
user = database.obtainCredentials(member.id, app="global")
if not user:
continue
try:
if member.nick.endswith('C1') or member.nick.endswith('C2'):
continue
except:
continue

wigor = apis.WigorServices()
wigor.login(user[0], user[1])
try:
edt = wigor.fetchAndParse('10/01/2023', toJson=True)
except apis.WigorServices.CurrentlyOnHoliday:
continue

for day in edt.keys():
if not edt[day]:
continue

classGrade = edt[day][0]['classGrade']
classLevel = classGrade['level']
classGroup = classGrade['group']

oldNick = member.nick or user[0].split('.')[0].title() + ' ' + user[0].split('.')[1][0].upper() + '.'
try:
await member.edit(nick="%s | %s %s" % (oldNick.split('|')[0].strip(), classLevel, classGroup))
except discord.Forbidden:
print("No permission to change nickname of %s" % member.name)



await interaction.followup.send(content="Successfully updated users!", ephemeral=True)


slash.add_command(Admin(name="admin", description="All bot administration slash commands"))
97 changes: 74 additions & 23 deletions views/inappoauth2.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,19 @@ class OAuthInApp_Input_modal(discord.ui.Modal, title="Connexion à 360Learning |
min_length=10,
custom_id="in_app_oauth2_password_input"
)
if not env.FETCH_USER_DETAILS:
firstname = discord.ui.TextInput(
placeholder="John",
label="Prénom :",
min_length=2,
custom_id="in_app_oauth2_firstname_input"
)
lastname = discord.ui.TextInput(
placeholder="Doe",
label="Nom :",
min_length=2,
custom_id="in_app_oauth2_lastname_input"
)

async def on_submit(self, interaction: discord.Interaction):
env.logger.debug("%s#%s (%i) submited OAuthInApp form." % (interaction.user.name, interaction.user.discriminator, interaction.user.id))
Expand All @@ -36,6 +49,14 @@ async def on_submit(self, interaction: discord.Interaction):
if child['custom_id'] == "in_app_oauth2_password_input":
password = child['value']

if not env.FETCH_USER_DETAILS:
if child['custom_id'] == "in_app_oauth2_firstname_input":
firstname = child['value']

if child['custom_id'] == "in_app_oauth2_lastname_input":
lastname = child['value']


if env.ASK_FOR_PASSWORD_ON_JOIN:
api = apis.WigorServices() #~ Might as well use ingenium API
try:
Expand All @@ -55,36 +76,66 @@ async def on_submit(self, interaction: discord.Interaction):
database.saveCredentials(interaction.user.id, 'global', username, None)

#~ ~ ~/ Rename user
status, user = await apis.epsi.getUserDetails(username)
if status != 200:
await interaction.followup.send(
content="`❌` Une erreur est survenue lors de la récupération de vos informations. Veuillez réessayer.",
view=OAuthInAppFailed_view(),
ephemeral=True
)
return
if env.FETCH_USER_DETAILS:
status, user = await apis.epsi.getUserDetails(username)
if status != 200:
await interaction.followup.send(
content="`❌` Une erreur est survenue lors de la récupération de vos informations. Veuillez réessayer.",
view=OAuthInAppFailed_view(),
ephemeral=True
)
return

isApprenant = False

firstname = user['prenom']
lastname = user['nom'][0]
classe = user['classe']
if classe == 'B1':
classe = 'SN1'
isApprenant = True
elif classe == 'B2':
classe = 'SN2'
isApprenant = True
elif classe == 'PROFS':
classe = 'Intervenant'
lastname = user['nom']
isApprenant = False

firstname = user['prenom']
lastname = user['nom']
classe = user['classe']
if classe == 'B1':
classe = 'SN1'
isApprenant = True
elif classe == 'B2':
classe = 'SN2'
isApprenant = True
elif classe == 'PROFS':
classe = 'Intervenant'
lastname = user['nom']

else:
#~ Let's fetch class
wigor = apis.WigorServices()
wigor.login(username, None)
try:
edt = wigor.fetchAndParse('10/01/2023', toJson=True)

for day in edt.keys():
if not edt[day]:
continue

classGrade = edt[day][0]['classGrade']
classLevel = classGrade['level']
classGroup = classGrade['group']

isApprenant = True

except apis.WigorServices.CurrentlyOnHoliday:
classLevel = '?'
classGroup = '?'
isApprenant = False

classe = "%s %s" % (classLevel, classGroup)


try:
await interaction.user.edit(nick="%s %s. | %s" % (firstname, lastname, classe))
await interaction.user.edit(nick="%s %s. | %s" % (firstname, lastname[0], classe))
except discord.errors.Forbidden:
env.logger.warning("Guild: %i // Failed to rename user %s#%s (%i)." % (interaction.guild.id, interaction.user.name, interaction.user.discriminator, interaction.user.id))


#~ ~ ~/ Save the user's infos
database.saveInfos(interaction.user.id, classe, firstname, lastname, None, None)


#~ ~ ~/ Give guild access permissions to the user
guild = interaction.guild
role = guild.get_role(database.obtainConfiguration(guild.id, "verifiedRole"))
Expand Down

0 comments on commit f49d6fb

Please sign in to comment.