def change_euro_eusko(request): """ Change d'€ en eusko pour un adhérent via un BDC. """ try: cyclos = CyclosAPI(token=request.user.profile.cyclos_token, mode='bdc') except CyclosAPIException: return Response({'error': 'Unable to connect to Cyclos!'}, status=status.HTTP_400_BAD_REQUEST) serializer = serializers.ChangeEuroEuskoSerializer(data=request.data) serializer.is_valid(raise_exception=True) # log.critical(serializer.errors) member_cyclos_id = cyclos.get_member_id_from_login(request.data['member_login']) try: dolibarr = DolibarrAPI(api_key=request.user.profile.dolibarr_token) dolibarr_member = dolibarr.get(model='members', sqlfilters="login='******'".format(request.data['member_login']))[0] except DolibarrAPIException: return Response({'error': 'Unable to connect to Dolibarr!'}, status=status.HTTP_400_BAD_REQUEST) except IndexError: return Response({'error': 'Unable to fetch Dolibarr data! Maybe your credentials are invalid!?'}, status=status.HTTP_400_BAD_REQUEST) if dolibarr_member['type'].lower() == 'particulier': member_name = '{} {}'.format(dolibarr_member['firstname'], dolibarr_member['lastname']) else: member_name = dolibarr_member['company'] # payment/perform query_data = { 'type': str(settings.CYCLOS_CONSTANTS['payment_types']['change_billets_versement_des_euro']), 'amount': request.data['amount'], 'currency': str(settings.CYCLOS_CONSTANTS['currencies']['euro']), 'from': 'SYSTEM', 'to': cyclos.user_bdc_id, # ID de l'utilisateur Bureau de change 'customValues': [ { 'field': str(settings.CYCLOS_CONSTANTS['transaction_custom_fields']['adherent']), 'linkedEntityValue': member_cyclos_id # ID de l'adhérent }, { 'field': str(settings.CYCLOS_CONSTANTS['transaction_custom_fields']['mode_de_paiement']), 'enumeratedValues': request.data['payment_mode'] # ID du mode de paiement (chèque ou espèces) }, ], # "Change - E12345 - Nom de l'adhérent - Mode de paiement" 'description': 'Change billets - {} - {} - {}'.format( request.data['member_login'], member_name, request.data['payment_mode_name']), } return Response(cyclos.post(method='payment/perform', data=query_data))
def reconversion(request): """ Reconversion eusko en euros pour un adhérent (prestataire) via un BDC. """ try: cyclos = CyclosAPI(token=request.user.profile.cyclos_token, mode='bdc') except CyclosAPIException: return Response({'error': 'Unable to connect to Cyclos!'}, status=status.HTTP_400_BAD_REQUEST) serializer = serializers.ReconversionSerializer(data=request.data) serializer.is_valid(raise_exception=True) # log.critical(serializer.errors) try: dolibarr = DolibarrAPI(api_key=request.user.profile.dolibarr_token) dolibarr_member = dolibarr.get(model='members', sqlfilters="login='******'".format(request.data['member_login']))[0] except DolibarrAPIException: return Response({'error': 'Unable to connect to Dolibarr!'}, status=status.HTTP_400_BAD_REQUEST) except IndexError: return Response({'error': 'Unable to fetch Dolibarr data! Maybe your credentials are invalid!?'}, status=status.HTTP_400_BAD_REQUEST) if dolibarr_member['type'].lower() == 'particulier': return Response({'error': 'Forbidden, reconversion is not available for non-business members!'}, status=status.HTTP_403_FORBIDDEN) member_cyclos_id = cyclos.get_member_id_from_login(request.data['member_login']) # payment/perform query_data = { 'type': str(settings.CYCLOS_CONSTANTS['payment_types']['reconversion_billets_versement_des_eusko']), 'amount': request.data['amount'], 'currency': str(settings.CYCLOS_CONSTANTS['currencies']['eusko']), 'from': 'SYSTEM', 'to': cyclos.user_bdc_id, # ID de l'utilisateur Bureau de change 'customValues': [ { 'field': str(settings.CYCLOS_CONSTANTS['transaction_custom_fields']['adherent']), 'linkedEntityValue': member_cyclos_id # ID de l'adhérent }, { 'field': str(settings.CYCLOS_CONSTANTS['transaction_custom_fields']['numero_de_facture']), 'stringValue': request.data['facture'] # ID Facture }, ], 'description': 'Reconversion - {} - {}'.format(request.data['member_login'], dolibarr_member['company']), } return Response(cyclos.post(method='payment/perform', data=query_data))
class MembersSubscriptionsAPIView(BaseAPIView): def __init__(self, **kwargs): super(MembersSubscriptionsAPIView, self).__init__(model='members/%_%/subscriptions') def create(self, request): data = request.data dolibarr_token = request.user.profile.dolibarr_token log.info("data: {}".format(data)) serializer = MembersSubscriptionsSerializer(data=data) if not serializer.is_valid(): log.critical("serializer.errors: {}".format(serializer.errors)) return Response({'error': 'Oops! Something is wrong in your request data: {}'.format(serializer.errors)}, status=status.HTTP_400_BAD_REQUEST) member_id = data.get('member_id', '') if not member_id: log.critical('A member_id must be provided!') return Response({'error': 'A member_id must be provided!'}, status=status.HTTP_400_BAD_REQUEST) # #841 : We need to connect to Cyclos before doing Dolibarr calls, making sure Cyclos token is still valid. # This way, we avoid creating a subscription in Dolibarr if it's not the case. try: self.cyclos = CyclosAPI(token=request.user.profile.cyclos_token, mode='bdc') except CyclosAPIException: return Response({'error': 'Unable to connect to Cyclos!'}, status=status.HTTP_400_BAD_REQUEST) try: member = self.dolibarr.get(model='members', id=member_id, api_key=dolibarr_token) except DolibarrAPIException as e: log.critical("member_id: {}".format(member_id)) log.critical(e) log.critical('This member_id was not found in the database!') return Response({'error': 'This member_id was not found in the database!'}, status=status.HTTP_400_BAD_REQUEST) data['start_date'] = Subscription.calculate_start_date(member['datefin']) data['end_date'] = Subscription.calculate_end_date(data['start_date']) data['label'] = Subscription.calculate_label(data['end_date']) log.info("data after: {}".format(data)) # Register new subscription data_res_subscription = {'start_date': data['start_date'], 'end_date': data['end_date'], 'amount': data['amount'], 'label': data['label']} self.model = self.model.replace('%_%', member_id) try: res_id_subscription = self.dolibarr.post( model=self.model, data=data_res_subscription, api_key=dolibarr_token) log.info("res_id_subscription: {}".format(res_id_subscription)) except DolibarrAPIException as e: log.critical("model: {}".format(self.model)) log.critical("data_res_subscription: {}".format(data_res_subscription)) log.critical(e) return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST) # Register new payment payment_account, payment_type, payment_label = Subscription.account_and_type_from_payment_mode(data['payment_mode']) # noqa if not payment_account or not payment_type: log.critical('This payment_mode is invalid!') return Response({'error': 'This payment_mode is invalid!'}, status=status.HTTP_400_BAD_REQUEST) data_res_payment = {'date': arrow.now('Europe/Paris').timestamp, 'type': payment_type, 'label': data['label'], 'amount': data['amount']} model_res_payment = 'bankaccounts/{}/lines'.format(payment_account) try: res_id_payment = self.dolibarr.post( model=model_res_payment, data=data_res_payment, api_key=dolibarr_token) log.info("res_id_payment: {}".format(res_id_payment)) except DolibarrAPIException as e: log.critical("model: {}".format(model_res_payment)) log.critical("data_res_payment: {}".format(data_res_payment)) log.critical(e) return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST) # Link this new subscription with this new payment data_link_sub_payment = {'fk_bank': res_id_payment} model_link_sub_payment = 'subscriptions/{}'.format(res_id_subscription) try: res_id_link_sub_payment = self.dolibarr.put( model=model_link_sub_payment, data=data_link_sub_payment, api_key=dolibarr_token) log.info("res_id_link_sub_payment: {}".format(res_id_link_sub_payment)) except DolibarrAPIException as e: log.critical("model: {}".format(model_link_sub_payment)) log.critical("data_link_sub_payment: {}".format(data_link_sub_payment)) log.critical(e) return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST) # Link this payment with the related-member data_link_payment_member = {'label': '{} {}'.format(member['firstname'], member['lastname']), 'type': 'member', 'url_id': member_id, 'url': '{}/adherents/card.php?rowid={}'.format( settings.DOLIBARR_PUBLIC_URL, member_id)} model_link_payment_member = 'bankaccounts/{}/lines/{}/links'.format(payment_account, res_id_payment) try: res_id_link_payment_member = self.dolibarr.post( model=model_link_payment_member, data=data_link_payment_member, api_key=dolibarr_token) log.info("res_id_link_payment_member: {}".format(res_id_link_payment_member)) except DolibarrAPIException as e: log.critical("model: {}".format(model_link_payment_member)) log.critical("data_link_payment_member: {}".format(data_link_payment_member)) log.critical(e) return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST) current_member = self.dolibarr.get(model='members', id=member_id, api_key=dolibarr_token) res = {'id_subscription': res_id_subscription, 'id_payment': res_id_payment, 'link_sub_payment': res_id_link_sub_payment, 'id_link_payment_member': res_id_link_payment_member, 'member': current_member} if current_member['type'].lower() in ('particulier', 'touriste'): member_name = '{} {}'.format(current_member['firstname'], current_member['lastname']) else: member_name = current_member['company'] # Get Cyclos member and create it if it does not exist. try: member_cyclos_id = self.cyclos.get_member_id_from_login(current_member['login']) except CyclosAPIException: log.debug("Member not found in Cyclos, will create it.") create_user_data = { 'group': str(settings.CYCLOS_CONSTANTS['groups']['adherents_sans_compte']), 'name': '{} {}'.format(current_member['firstname'], current_member['lastname']), 'username': current_member['login'], 'skipActivationEmail': True, } log.debug("create_user_data = {}".format(create_user_data)) response_data = self.cyclos.post(method='user/register', data=create_user_data) member_cyclos_id = response_data['result']['user']['id'] log.debug("member_cyclos_id = {}".format(member_cyclos_id)) # Cyclos: Register member subscription payment query_data = {} if 'Eusko' in data['payment_mode']: query_data.update( {'type': str(settings.CYCLOS_CONSTANTS['payment_types']['cotisation_en_eusko']), 'currency': str(settings.CYCLOS_CONSTANTS['currencies']['eusko']), 'customValues': [ {'field': str(settings.CYCLOS_CONSTANTS['transaction_custom_fields']['adherent']), 'linkedEntityValue': member_cyclos_id}], 'description': 'Cotisation - {} - {}'.format( current_member['login'], member_name), }) currency = 'eusko' elif 'Euro' in data['payment_mode']: query_data.update( {'type': str(settings.CYCLOS_CONSTANTS['payment_types']['cotisation_en_euro']), 'currency': str(settings.CYCLOS_CONSTANTS['currencies']['euro']), 'customValues': [ {'field': str(settings.CYCLOS_CONSTANTS['transaction_custom_fields']['adherent']), 'linkedEntityValue': member_cyclos_id}, {'field': str(settings.CYCLOS_CONSTANTS['transaction_custom_fields']['mode_de_paiement']), 'enumeratedValues': data['cyclos_id_payment_mode']}], 'description': 'Cotisation - {} - {} - {}'.format( current_member['login'], member_name, payment_label), }) currency = '€' else: return Response({'error': 'This payment_mode is invalid!'}, status=status.HTTP_400_BAD_REQUEST) query_data.update({ 'amount': data['amount'], 'from': 'SYSTEM', 'to': self.cyclos.user_bdc_id, # ID de l'utilisateur Bureau de change }) self.cyclos.post(method='payment/perform', data=query_data) return Response(res, status=status.HTTP_201_CREATED) def update(self, request, pk=None): pass def partial_update(self, request, pk=None): pass def destroy(self, request, pk): pass
def retrait_eusko_numerique(request): """ Retrait eusko: numerique vers billets """ try: cyclos = CyclosAPI(token=request.user.profile.cyclos_token, mode='bdc') except CyclosAPIException: return Response({'error': 'Unable to connect to Cyclos!'}, status=status.HTTP_400_BAD_REQUEST) serializer = serializers.RetraitEuskoNumeriqueSerializer(data=request.data) serializer.is_valid(raise_exception=True) # log.critical(serializer.errors) member_cyclos_id = cyclos.get_member_id_from_login(request.data['member_login']) try: dolibarr = DolibarrAPI(api_key=request.user.profile.dolibarr_token) dolibarr_member = dolibarr.get(model='members', sqlfilters="login='******'".format(request.data['member_login']))[0] except DolibarrAPIException: return Response({'error': 'Unable to connect to Dolibarr!'}, status=status.HTTP_400_BAD_REQUEST) except IndexError: return Response({'error': 'Unable to fetch Dolibarr data! Maybe your credentials are invalid!?'}, status=status.HTTP_400_BAD_REQUEST) if dolibarr_member['type'].lower() == 'particulier': member_name = '{} {}'.format(dolibarr_member['firstname'], dolibarr_member['lastname']) else: member_name = dolibarr_member['company'] # Verify whether or not member account has enough money member_account_summary_query = [member_cyclos_id, None] # ID de l'adhérent member_account_summary_res = cyclos.post(method='account/getAccountsSummary', data=member_account_summary_query) try: if (member_account_summary_res['result'][0]['type']['id'] != str(settings.CYCLOS_CONSTANTS['account_types']['compte_d_adherent'])): return Response({'error': "Unable to fetch account data!"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) except (KeyError, IndexError): return Response({'error': "Unable to fetch account data!"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) try: if float(member_account_summary_res['result'][0]['status']['balance']) < float(request.data['amount']): return Response({'error': "error-member-not-enough-money"}) except (KeyError, IndexError): return Response({'error': "Unable to fetch account data!"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) # Verify whether or not bdc cash stock have enough money bdc_account_summary_query = [cyclos.user_bdc_id, None] # ID de l'utilisateur Bureau de change bdc_account_summary_res = cyclos.post(method='account/getAccountsSummary', data=bdc_account_summary_query) bdc_account_summary_data = [ item for item in bdc_account_summary_res['result'] if item['type']['id'] == str(settings.CYCLOS_CONSTANTS['account_types']['stock_de_billets_bdc'])][0] if float(bdc_account_summary_data['status']['balance']) < float(request.data['amount']): return Response({'error': "error-bureau-not-enough-money"}) # Débit du compte debit_compte_data = { 'type': str(settings.CYCLOS_CONSTANTS['payment_types']['retrait_du_compte']), 'amount': request.data['amount'], # montant saisi 'currency': str(settings.CYCLOS_CONSTANTS['currencies']['eusko']), 'from': member_cyclos_id, # ID de l'adhérent 'to': 'SYSTEM', 'customValues': [ { 'field': str(settings.CYCLOS_CONSTANTS['transaction_custom_fields']['bdc']), 'linkedEntityValue': cyclos.user_bdc_id, # ID de l'utilisateur Bureau de change }, ], 'description': 'Retrait', } cyclos.post(method='payment/perform', data=debit_compte_data) # Retrait des billets retrait_billets_data = { 'type': str(settings.CYCLOS_CONSTANTS['payment_types']['retrait_de_billets']), 'amount': request.data['amount'], # montant saisi 'currency': str(settings.CYCLOS_CONSTANTS['currencies']['eusko']), 'from': cyclos.user_bdc_id, # ID de l'utilisateur Bureau de change 'to': 'SYSTEM', 'customValues': [ { 'field': str(settings.CYCLOS_CONSTANTS['transaction_custom_fields']['adherent']), 'linkedEntityValue': member_cyclos_id, # ID de l'adhérent }, ], 'description': 'Retrait - {} - {}'.format(request.data['member_login'], member_name), } cyclos.post(method='payment/perform', data=retrait_billets_data) return Response(retrait_billets_data)
def depot_eusko_numerique(request): """ depot-eusko-numerique """ try: cyclos = CyclosAPI(token=request.user.profile.cyclos_token, mode='bdc') except CyclosAPIException: return Response({'error': 'Unable to connect to Cyclos!'}, status=status.HTTP_400_BAD_REQUEST) serializer = serializers.DepotEuskoNumeriqueSerializer(data=request.data) serializer.is_valid(raise_exception=True) # log.critical(serializer.errors) member_cyclos_id = cyclos.get_member_id_from_login(request.data['member_login']) try: dolibarr = DolibarrAPI(api_key=request.user.profile.dolibarr_token) dolibarr_member = dolibarr.get(model='members', sqlfilters="login='******'".format(request.data['member_login']))[0] except DolibarrAPIException: return Response({'error': 'Unable to connect to Dolibarr!'}, status=status.HTTP_400_BAD_REQUEST) except IndexError: return Response({'error': 'Unable to fetch Dolibarr data! Maybe your credentials are invalid!?'}, status=status.HTTP_400_BAD_REQUEST) if dolibarr_member['type'].lower() == 'particulier': member_name = '{} {}'.format(dolibarr_member['firstname'], dolibarr_member['lastname']) else: member_name = dolibarr_member['company'] # Retour des Eusko billets retour_eusko_billets_data = { 'type': str(settings.CYCLOS_CONSTANTS['payment_types']['depot_de_billets']), 'amount': request.data['amount'], # montant saisi 'currency': str(settings.CYCLOS_CONSTANTS['currencies']['eusko']), 'from': 'SYSTEM', 'to': cyclos.user_bdc_id, # ID de l'utilisateur Bureau de change 'customValues': [ { 'field': str(settings.CYCLOS_CONSTANTS['transaction_custom_fields']['adherent']), 'linkedEntityValue': member_cyclos_id # ID de l'adhérent }, ], 'description': 'Dépôt - {} - {}'.format(request.data['member_login'], member_name), } cyclos.post(method='payment/perform', data=retour_eusko_billets_data) # Crédit du compte Eusko numérique du prestataire depot_eusko_numerique_data = { 'type': str(settings.CYCLOS_CONSTANTS['payment_types']['credit_du_compte']), 'amount': request.data['amount'], # montant saisi 'currency': str(settings.CYCLOS_CONSTANTS['currencies']['eusko']), 'from': 'SYSTEM', 'to': member_cyclos_id, # ID de l'adhérent 'customValues': [ { 'field': str(settings.CYCLOS_CONSTANTS['transaction_custom_fields']['bdc']), 'linkedEntityValue': cyclos.user_bdc_id, # ID de l'utilisateur Bureau de change }, ], 'description': 'Dépôt', } cyclos.post(method='payment/perform', data=depot_eusko_numerique_data) return Response(depot_eusko_numerique_data)
def perform(request): """ perform """ try: cyclos = CyclosAPI(token=request.user.profile.cyclos_token) except CyclosAPIException: return Response({'error': 'Unable to connect to Cyclos!'}, status=status.HTTP_400_BAD_REQUEST) serializer = serializers.GenericHistoryValidationSerializer(data=request.data) serializer.is_valid(raise_exception=True) # log.critical(serializer.errors) for payment in serializer.data['selected_payments']: try: adherent_cyclos_id = cyclos.get_member_id_from_login(member_login=payment['adherent_id']) # Determine whether or not our user is part of the appropriate group group_constants_with_account = [str(settings.CYCLOS_CONSTANTS['groups']['adherents_prestataires']), str(settings.CYCLOS_CONSTANTS['groups']['adherents_utilisateurs'])] # Fetching info for our current user (we look for his groups) user_data = cyclos.post(method='user/load', data=[adherent_cyclos_id]) if not user_data['result']['group']['id'] in group_constants_with_account: error = "{} n'a pas de compte Eusko numérique...".format(payment['adherent_id']) log.critical(error) echeance = models.Echeance.objects.get(ref=payment['ref']) echeance.cyclos_error = error echeance.save() continue # Payment in Euro change_numerique_euro = { 'type': str(settings.CYCLOS_CONSTANTS['payment_types']['change_numerique_en_ligne_versement_des_euro']), # noqa 'amount': float(payment['montant']), 'currency': str(settings.CYCLOS_CONSTANTS['currencies']['euro']), 'from': 'SYSTEM', 'to': str(settings.CYCLOS_CONSTANTS['users']['compte_dedie_eusko_numerique']), 'customValues': [{ 'field': str(settings.CYCLOS_CONSTANTS['transaction_custom_fields']['numero_de_transaction_banque']), # noqa 'stringValue': payment['ref'] # référence de l'échéance }], 'description': 'Change par prélèvement automatique' } cyclos.post(method='payment/perform', data=change_numerique_euro) # Payment in Eusko change_prelevement_auto = { 'type': str(settings.CYCLOS_CONSTANTS['payment_types']['change_numerique_en_ligne_versement_des_eusko']), # noqa 'amount': float(payment['montant']), 'currency': str(settings.CYCLOS_CONSTANTS['currencies']['eusko']), 'from': 'SYSTEM', 'to': adherent_cyclos_id, 'customValues': [{ 'field': str(settings.CYCLOS_CONSTANTS['transaction_custom_fields']['numero_de_transaction_banque']), # noqa 'stringValue': payment['ref'] # référence de l'échéance }], 'description': 'Change par prélèvement automatique' } change_prelevement_auto_id = cyclos.post(method='payment/perform', data=change_prelevement_auto) echeance = models.Echeance.objects.get(ref=payment['ref']) echeance.cyclos_payment_id = change_prelevement_auto_id['result']['id'] echeance.cyclos_error = '' echeance.save() except Exception as e: echeance = models.Echeance.objects.get(ref=payment['ref']) echeance.cyclos_error = str(e) echeance.save() return Response(serializer.data['selected_payments'])
def validate_lost_password(request): """ validate_lost_password """ serializer = serializers.ValidLostPasswordSerializer(data=request.data) serializer.is_valid( raise_exception=True) # log.critical(serializer.errors) try: token_data = jwt.decode(request.data['token'], settings.JWT_SECRET, issuer='lost-password', audience='guest') except jwt.InvalidTokenError: return Response({'error': 'Unable to read token!'}, status=status.HTTP_400_BAD_REQUEST) try: # Check SecurityQA with custom methods in models.SecurityAnswer answer = models.SecurityAnswer.objects.get(owner=token_data['login']) if not answer.check_answer(serializer.data['answer']): return Response({'status': 'NOK'}, status=status.HTTP_400_BAD_REQUEST) # Dans Cyclos, activer l'utilisateur (au cas où il soit à l'état bloqué) cyclos = CyclosAPI(mode='login') cyclos_token = cyclos.login(auth_string=b64encode( bytes( '{}:{}'.format(settings.APPS_ANONYMOUS_LOGIN, settings.APPS_ANONYMOUS_PASSWORD), 'utf-8')).decode('ascii')) cyclos_user_id = cyclos.get_member_id_from_login( member_login=token_data['login'], token=cyclos_token) active_user_data = { 'user': cyclos_user_id, # ID de l'utilisateur 'status': 'ACTIVE' } cyclos.post(method='userStatus/changeStatus', data=active_user_data, token=cyclos_token) # Dans Cyclos, reset le mot de passe d'un utilisateur password_data = { 'user': cyclos_user_id, # ID de l'utilisateur 'type': str(settings.CYCLOS_CONSTANTS['password_types']['login_password']), 'newPassword': serializer.data['new_password'], # saisi par l'utilisateur 'confirmNewPassword': serializer.data['confirm_password'], # saisi par l'utilisateur } cyclos.post(method='password/change', data=password_data, token=cyclos_token) return Response({'status': 'success'}) except (EuskalMonetaAPIException, CyclosAPIException, KeyError, IndexError): return Response({'error': 'Unable to get user data for this login!'}, status=status.HTTP_400_BAD_REQUEST)
def validate_first_connection(request): """ validate_first_connection """ serializer = serializers.ValidFirstConnectionSerializer(data=request.data) serializer.is_valid( raise_exception=True) # log.critical(serializer.errors) try: token_data = jwt.decode(request.data['token'], settings.JWT_SECRET, issuer='first-connection', audience='guest') except jwt.InvalidTokenError: return Response({'error': 'Unable to read token!'}, status=status.HTTP_400_BAD_REQUEST) try: dolibarr = DolibarrAPI() dolibarr_token = dolibarr.login( login=settings.APPS_ANONYMOUS_LOGIN, password=settings.APPS_ANONYMOUS_PASSWORD) # We check if the user already exist, if he already exist we return a 400 try: dolibarr.get(model='users', login=token_data['login'], api_key=dolibarr_token) return Response({'error': 'User already exist!'}, status=status.HTTP_201_CREATED) except DolibarrAPIException: pass # 1) Créer une réponse à une SecurityQuestion (créer aussi une SecurityAnswer). if serializer.data.get('question_id', False): # We got a question_id q = models.SecurityQuestion.objects.get( id=serializer.data['question_id']) elif serializer.data.get('question_text', False): # We didn't got a question_id, but a question_text: we need to create a new SecurityQuestion object q = models.SecurityQuestion.objects.create( question=serializer.data['question_text']) else: return Response( { 'status': ('Error: You need to provide at least one thse two fields: ' 'question_id or question_text') }, status=status.HTTP_400_BAD_REQUEST) res = models.SecurityAnswer.objects.create(owner=token_data['login'], question=q) res.set_answer(raw_answer=serializer.data['answer']) res.save() if not res: Response({'error': 'Unable to save security answer!'}, status=status.HTTP_400_BAD_REQUEST) # 2) Dans Dolibarr, créer un utilisateur lié à l'adhérent member = dolibarr.get(model='members', login=token_data['login'], api_key=dolibarr_token) create_user = '******'.format(member[0]['id']) create_user_data = {'login': token_data['login']} # user_id will be the ID for this new user user_id = dolibarr.post(model=create_user, data=create_user_data, api_key=dolibarr_token) # 3) Dans Dolibarr, ajouter ce nouvel utilisateur dans le groupe "Adhérents" user_group_model = 'users/{}/setGroup/{}'.format( user_id, settings.DOLIBARR_CONSTANTS['groups']['adherents']) user_group_res = dolibarr.get(model=user_group_model, api_key=dolibarr_token) if not user_group_res == 1: raise EuskalMonetaAPIException # 4) Dans Cyclos, activer l'utilisateur cyclos = CyclosAPI(mode='login') cyclos_token = cyclos.login(auth_string=b64encode( bytes( '{}:{}'.format(settings.APPS_ANONYMOUS_LOGIN, settings.APPS_ANONYMOUS_PASSWORD), 'utf-8')).decode('ascii')) cyclos_user_id = cyclos.get_member_id_from_login( member_login=token_data['login'], token=cyclos_token) active_user_data = { 'user': cyclos_user_id, # ID de l'utilisateur 'status': 'ACTIVE' } cyclos.post(method='userStatus/changeStatus', data=active_user_data, token=cyclos_token) # 5) Dans Cyclos, initialiser le mot de passe d'un utilisateur password_data = { 'user': cyclos_user_id, # ID de l'utilisateur 'type': str(settings.CYCLOS_CONSTANTS['password_types']['login_password']), 'newPassword': request.data['new_password'], # saisi par l'utilisateur 'confirmNewPassword': request.data['confirm_password'], # saisi par l'utilisateur } cyclos.post(method='password/change', data=password_data, token=cyclos_token) return Response({'status': 'success'}) except (EuskalMonetaAPIException, DolibarrAPIException, CyclosAPIException, KeyError, IndexError): return Response({'error': 'Unable to get user data for this login!'}, status=status.HTTP_400_BAD_REQUEST)