basic registration and auth tokens

This commit is contained in:
b1ek 2023-05-16 23:40:32 +10:00
parent ecc8762c56
commit bac279ae9e
Signed by: blek
GPG Key ID: 14546221E3595D0C
3 changed files with 44 additions and 19 deletions

View File

@ -17,22 +17,31 @@ class Migration(migrations.Migration):
name='User', name='User',
fields=[ fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('favorites_apartments', models.CharField(max_length=100, help_text="Избранные квартиры (CSV)")), ('favorites_apartments', models.CharField(max_length=100, help_text="Избранные квартиры (CSV)", null=True)),
('comparison_apartments', models.CharField(max_length=100, help_text="Квартиры для сравнения (CSV)")), ('comparison_apartments', models.CharField(max_length=100, help_text="Квартиры для сравнения (CSV)", null=True)),
('name', models.CharField(max_length=256, help_text='ФИО Пользователя')), ('name', models.CharField(max_length=500, help_text='ФИО Пользователя', null=True)),
('date_of_birth', models.DateField(help_text='Дата рождения пользователя')), ('date_of_birth', models.DateField(help_text='Дата рождения пользователя', null=True)),
('about_me', models.CharField(max_length=1000, help_text='Поле "О Себе"')), ('about_me', models.CharField(max_length=1000, help_text='Поле "О Себе"', null=True)),
('gender', models.CharField(max_length=1, help_text='Пол пользователя (f,m,n,?)')), ('gender', models.CharField(max_length=1, help_text='Пол пользователя (f,m,n,?)', null=True)),
('phone', models.CharField(max_length=30, help_text='Телефон пользователя в международном формате (+00000000)', null=True)), ('phone', models.CharField(max_length=30, help_text='Телефон пользователя в международном формате (+00000000)', null=True)),
('email', models.CharField(max_length=1000, help_text='Почтовый ящик пользователя в формате user@example.com', null=True)), ('email', models.CharField(max_length=1000, help_text='Почтовый ящик пользователя в формате user@example.com', null=True)),
('telegram', models.CharField(max_length=1000, help_text='Телеграм пользователя', null=True)), ('telegram', models.CharField(max_length=1000, help_text='Телеграм пользователя', null=True)),
('discord', models.CharField(max_length=1000, help_text='Дискорд ник пользователя', null=True)), ('discord', models.CharField(max_length=1000, help_text='Дискорд ник пользователя', null=True)),
('city', models.CharField(max_length=1000, help_text='Город пользователя', null=True)), ('city', models.CharField(max_length=1000, help_text='Город пользователя', null=True)),
('role', models.CharField(max_length=1, help_text='Роль пользователя (s - student, a - admin, m - moderator)', null=False)), ('role', models.CharField(max_length=1, help_text='Роль пользователя (s - student, a - admin, m - moderator)', null=False)),
('photo_provider', models.CharField(max_length=100, verbose_name='Сервис, из которого загружается фотография пользователя (VVSU, GRAVATAR)')), ('photo_provider', models.CharField(max_length=100, verbose_name='Сервис, из которого загружается фотография пользователя (VVSU, GRAVATAR)', null=True)),
('openid_addr', models.CharField(max_length=1000, null=False, help_text='Адрес Open ID Connect (login@provider.com, для ВВГУ - login@vvsu.ru)')), ('openid_addr', models.CharField(max_length=1000, null=False, help_text='Адрес Open ID Connect (login@provider.com, для ВВГУ - login@vvsu.ru)')),
('openid_id', models.CharField(max_length=5000, verbose_name='ID Пользователя в системе провайдера авторизации (скорее всего ВВГУ)')) ('openid_id', models.CharField(max_length=5000, null=False, verbose_name='ID Пользователя в системе провайдера авторизации (скорее всего ВВГУ)'))
]
),
migrations.CreateModel(
name='AuthTokens',
fields=[
('user', models.BigIntegerField(null=False, verbose_name='ID Пользователя, которому принадлежит токен')),
('key', models.TextField(verbose_name='Ключ API')),
('expires', models.BigIntegerField(verbose_name='Когда ключ истечет (Unix timestamp)')),
('ip', models.CharField(max_length=16, verbose_name='IP, с которого был создан ключ'))
] ]
) )
] ]

View File

@ -130,3 +130,9 @@ class PsychTestAnswers(models.Model):
class Meta: class Meta:
verbose_name = "Ответ на психологический тест" verbose_name = "Ответ на психологический тест"
verbose_name_plural = "Ответы на психологический тест" verbose_name_plural = "Ответы на психологический тест"
class AuthTokens(models.Model):
user = models.BigIntegerField(null=False, verbose_name='ID Пользователя, которому принадлежит токен');
key = models.TextField(verbose_name='Ключ API');
expires = models.BigIntegerField(verbose_name='Когда ключ истечет (Unix timestamp)');
ip = models.CharField(max_length=16, verbose_name='IP, с которого был создан ключ');

View File

@ -171,12 +171,12 @@ def VVSUAuthProxy(req: Request):
return resp; return resp;
def regiserUser(oid, provider_id, name, date_of_birth): def register(oid, provider_id, name):
user = User( user = User(
favorites_apartments='', favorites_apartments='',
comparison_apartments='', comparison_apartments='',
name=name, name=name,
date_of_birth=date_of_birth, # date_of_birth=,
about_me='', about_me='',
gender='?', gender='?',
phone='+00000', phone='+00000',
@ -188,7 +188,9 @@ def regiserUser(oid, provider_id, name, date_of_birth):
# photo_provider=, # photo_provider=,
openid_addr=oid, openid_addr=oid,
openid_id=provider_id, openid_id=provider_id,
) );
user.save();
return user;
def get_oauth_token(remote, data): def get_oauth_token(remote, data):
return requests.post(remote + '/oauth2/token', data, return requests.post(remote + '/oauth2/token', data,
@ -234,32 +236,40 @@ class UserLogin(APIView):
# 'client_secret': 'U8y@uPVee6Q^*729esHTo4Vd' # 'client_secret': 'U8y@uPVee6Q^*729esHTo4Vd'
# }); # });
auth_data = {'access_token': '5kHvrjy91LJgJLKitejBBG24c7JiX45tEstKVHRpfHc._WQDwQ2F13aytbGFjlGnjXJeUWcDD1V3om3cRW0IujM', 'expires_in': 3600, 'id_token': 'eyJhbGciOiJSUzI1NiIsImtpZCI6InB1YmxpYzpoeWRyYS5vcGVuaWQuaWQtdG9rZW4iLCJ0eXAiOiJKV1QifQ.eyJhY3IiOiIwIiwiYXRfaGFzaCI6IjRMR1dRekxVaXFodUVTYjU0QWFIM0EiLCJhdWQiOlsiaXQtaHViLWNsaWVudCJdLCJhdXRoX3RpbWUiOjE2ODQyMzc4MDksImNhbGxiYWNrX3VybCI6IiIsImV4cCI6MTY4NDI0MTQ1NSwiZmFtaWx5X25hbWUiOiLQn9GD0YHRgtC-0LLQsNC70L7QsiIsImdpdmVuX25hbWUiOiLQndC40LrQuNGC0LAiLCJpYXQiOjE2ODQyMzc4NTUsImlkIjoiMDk2Qzc4Q0QtNDk0My00RDU3LUJDNkQtNUNERTEyRjY4NkUzIiwiaXNzIjoiaHR0cHM6Ly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hjtinQFp6XJ-Rh3JrmIfLAQ7DEUSOldMQ1xUw9GeHo_0sIsnjaM6lVx6M_SiDTWihxNu58DiI8tmvkdw7in95OJRoJZ30EhR3SGYsK3b51qdYK1aieufJHX40bN_S1gc84pisTg58z-zC5kGsjsZNv6gRSTO4oOpZMK1FMjv7HyasSMWEu-J052X4Qxquj4pWglpiGQNt3-E0jZUUjqmZ0-7AYiyEC_3IItBqWrve-LTXRF5faIZB5v3F3urY6Qjgn93m_AoK1oujfNAPk8WOLTv419CuC2fAc', 'scope': 'openid vvsu_IdUser vvsu_IdEmpl vvsu_IdStud vvsu_login given_name family_name', 'token_type': 'bearer'} auth_data = {'access_token': 'gcH96CSYQBeiq9te1lpJV4T9mBH4UabT4_m6fJQFQK4.K4GA7sXFtBEM26kDladZjZ8phsI3aRPmqu5oRts4Csg', 'expires_in': 3600, 'id_token': 'eyJhbGciOiJSUzI1NiIsImtpZCI6InB1YmxpYzpoeWRyYS5vcGVuaWQuaWQtdG9rZW4iLCJ0eXAiOiJKV1QifQ.eyJhY3IiOiIwIiwiYXRfaGFzaCI6ImJIZS1pWmlvX2Npa3diOFc3bnBkbEEiLCJhdWQiOlsiaXQtaHViLWNsaWVudCJdLCJhdXRoX3RpbWUiOjE2ODQyNDM0NjUsImNhbGxiYWNrX3VybCI6IiIsImV4cCI6MTY4NDI0NzA3MywiZmFtaWx5X25hbWUiOiLQn9GD0YHRgtC-0LLQsNC70L7QsiIsImdpdmVuX25hbWUiOiLQndC40LrQuNGC0LAiLCJpYXQiOjE2ODQyNDM0NzMsImlkIjoiMDk2Qzc4Q0QtNDk0My00RDU3LUJDNkQtNUNERTEyRjY4NkUzIiwiaXNzIjoiaHR0cHM6Ly93d3cudnZzdS5ydS9jb25uZWN0LyIsImp0aSI6IjU5M2FiYTQzLTU4OTQtNGZmNy1iMmU1LTdmOWZkYTZjZjFhZSIsImxvZ2luIjoiaHR0cHM6Ly9vcGVuaWQudnZzdS5ydS9ibGVrX18iLCJvcGVuaW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PsZdr9gj58jBYD8c1foXZ9I_KzC_bYDOyUQfjec5njxGWN3828TvySclHkXMUgQxCM16OmPq8MICk_tfhqOSezcs0JpXIEtHHn0h9HNavZuhMTIaTWErYRIIxEPgtBn8r8', 'scope': 'openid vvsu_IdUser vvsu_IdEmpl vvsu_IdStud vvsu_login given_name family_name', 'token_type': 'bearer'}
# print(auth_data);
if ('error' in auth_data):
return JsonResponse(auth_data);
user = None; user = None;
new_user = False; new_user = False;
print(auth_data); # vvsu_data = get_oauth_data('https://vvsu.ru/connect', auth_data['access_token']);
vvsu_data = {'acr': '0', 'aud': ['it-hub-client'], 'auth_time': 1684243465, 'callback_url': '', 'family_name': 'Пустовалов', 'given_name': 'Никита', 'iat': 1684243466, 'id': '096C78CD-4943-4D57-BC6D-5CDE12F686E3', 'iss': 'https://www.vvsu.ru/connect/', 'login': 'https://openid.vvsu.ru/blek__', 'openid': 'https://openid.vvsu.ru/blek__', 'picture': 'https://www.vvsu.ru/oiskp/photo/pth.asp?ID=096C78CD-4943-4D57-BC6D-5CDE12F686E3&', 'profile_url': None, 'rat': 1684243454, 'sub': 'https://openid.vvsu.ru/blek__', 'surname': 'Пустовалов', 'title': 'Студент', 'vvsu_IdEmpl': None, 'vvsu_IdStud': '197080', 'vvsu_IdUser': 190489, 'vvsu_login': 'blek__'}
return JsonResponse(get_oauth_data('https://vvsu.ru/connect', auth_data['access_token'])); if ('error' in vvsu_data):
res = JsonResponse(vvsu_data);
res.status_code = 500;
return res;
req.session['auth_data'] = vvsu_data; req.session['auth_data'] = vvsu_data;
if ('error' in vvsu_data): if ('error' in vvsu_data):
res = JsonResponse(vvsu_data); res = JsonResponse(vvsu_data);
res.status_code = cb.status_code; res.status_code = 500;
return res return res
vvsu_data['vvsu_login'] += '@vvsu.ru'; vvsu_data['vvsu_login'] += '@vvsu.ru';
try: try:
user = User.objects.get(openid_addr=vvsu_data['vvsu_login']); user = User.objects.get(openid_addr=vvsu_data['vvsu_login']);
except User.DoesNotExist: except User.DoesNotExist:
registerUser(vvsu_data['vvsu_login'], cb.id, f'{cb.given_name} {cb.family_name}'); user = register(vvsu_data['vvsu_login'], vvsu_data['id'], f"{vvsu_data['given_name']} {vvsu_data['family_name']}");
user = User.objects.get(openid_addr=vvsu_data['vvsu_login']);
new_user = True; new_user = True;
return JsonResponse({ return JsonResponse({
'user_data': user, 'user_data': PublicUserSerializer(user).data,
'new_user': new_user 'new_user': new_user
}); });