Exemplo n.º 1
0
def create_user_from_files(repository):
    """Recria os usúarios do repositório, baseado nos arquivos json"""
    mucuas = get_available_mucuas(None, repository)

    for mucua in mucuas:
        if not mucua[1] == 'web':
            if not mucua[1] == '':
                mocambola_path = os.path.join(str(REPOSITORY_DIR),
                                              str(repository.name),
                                              str(mucua[1]), MOCAMBOLA_DIR)

                if not os.path.exists(mocambola_path):
                    os.makedirs(mocambola_path)

                for jmocambola in os.listdir(mocambola_path):
                    mocambola_json_file = open(
                        os.path.join(mocambola_path, jmocambola))
                    data = JSONParser().parse(mocambola_json_file)
                    u = User()
                    serializer = UserSerializer(u, data=data)
                    logger.debug("Checking user " + u.username)

                    if serializer.errors:
                        logger.debug(
                            u"%s %s" %
                            (_('Error deserializing'), serializer.errors))
                    serializer.is_valid()

                    current_user = serializer.object
                    try:
                        User.objects.get(username=current_user.username)
                    except ObjectDoesNotExist:
                        current_user.save()
                        logger.debug("User " + current_user.username +
                                     " saved!")
Exemplo n.º 2
0
def create_auth(request):
    serialized = UserSerializer(data=request.DATA)
    if serialized.is_valid():
        User.objects.create_user(username=serialized.init_data['username'],
                                 password=serialized.init_data['password'],
                                 email=serialized.init_data['email'])
        return Response(serialized.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 3
0
def mocambola_post_save(instance, **kwargs):
    """Intercepta o sinal de *post_save* do Mocambola, serialize a adiciona o
    objeto ao repositorio."""

    serializer = UserSerializer(instance.user)
    mocambolapath = get_file_path(instance) + '/'
    mocamboladata = instance.user.get_username() + '.json'
    check_if_path_exists_or_create(mocambolapath)
    fout = open(mocambolapath + mocamboladata, 'w')
    fout.write(str(serializer.getJSON()))
    fout.close()
    git_add(mocamboladata, mocambolapath)
    git_commit(mocamboladata, instance.user.get_username(),
               instance.user.email, instance.repository.get_path())
Exemplo n.º 4
0
def mocambola_detail(request, repository, mucua, mocambola):
    # retorna detalhes do user

    try:
        user = User.objects.get(username=mocambola)
    except User.DoesNotExist:
        response_data = {
            'error': True,
            'errorMessage': _('User don\t exists')
        }
            
        return HttpResponse(json.dumps(response_data), mimetype=u'application/json')

    # TODO: verificar questao abaixo:
    #  atualmente, esta serializando o user
    #  possivelmente, teria que ter um serializer especifico para mocambola
    #  deixando em aberto

    # serializa e da saida
    serializer = UserSerializer(user)
    return Response(serializer.data)
Exemplo n.º 5
0
def login(request):
    if request.method == 'GET':
        # gera token para tela de login
        c = RequestContext(request, {'autoescape': False})
        c.update(csrf(request))
        t = Template('{ "csrftoken": "{{ csrf_token  }}" }')
        return HttpResponse(t.render(c), mimetype=u'application/json')

    elif request.method == 'POST':
        username = request.DATA['username'] + '@' + request.DATA[
            'mucua'] + '.' + request.DATA['repository'] + '.net'
        password = request.DATA['password']
        fileBackend = FileBackend()
        authenticate = fileBackend.authenticate(username, password)

        # TODO: get this data from logger or bbx/auth.py,
        # so the next section won't be needed anymore
        if (authenticate):
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                logger.debug(u"%s" % (_('Exception caught, UserDoesNotExist')))
            if user:
                serializer = UserSerializer(user)
                return Response(serializer.data)
            else:
                response_data = {'errorMessage': 'Usuario inexistente.'}
                return HttpResponse(json.dumps(response_data),
                                    mimetype=u'application/json')
        else:
            response_data = {
                'error': True,
                'errorMessage': 'Usuario ou senha invalid@s.',
            }

            return HttpResponse(json.dumps(response_data),
                                mimetype=u'application/json')
Exemplo n.º 6
0
    def authenticate(self, username=None, password=None):
        match = re.findall("(.*)@(.*)\.(.*)\.(.*)$", username)
        if match:
            (current_mocambola, current_mucua, current_repository,
             term) = match[0]
            # verifica se mucua e repositorio sao validos
            try:
                current_mucua = Mucua.objects.get(description=current_mucua)
            except Mucua.DoesNotExist:
                return None
            try:
                current_repository = Repository.objects.get(
                    name=current_repository)
            except Repository.DoesNotExist:
                return None
        else:
            print "invalid address"
            return None
        # Get file from MOCAMBOLA_DIR
        mocambola_path = os.path.join(str(REPOSITORY_DIR),
                                      str(current_repository),
                                      str(current_mucua), MOCAMBOLA_DIR)
        print "Mocambola Path: " + mocambola_path

        for jmocambola in os.listdir(mocambola_path):

            if jmocambola == username + '.json':
                # Deserialize the customized User object
                mocambola_json_file = open(
                    os.path.join(mocambola_path, jmocambola))
                data = JSONParser().parse(mocambola_json_file)
                u = User()
                serializer = UserSerializer(u, data=data)
                if serializer.errors:
                    logger.debug(u"%s %s" %
                                 (_('Error deserialing'), serializer.errors))
                serializer.is_valid()

                current_user = serializer.object
                login_valid = (username == current_user.username)
                pwd_valid = check_password(password, current_user.password)
                if login_valid and pwd_valid:
                    logger.info(u"%s %s %s" %
                                (_('User'), current_mocambola, _('logged in')))
                    try:
                        user = User.objects.get(username=username)
                    except User.DoesNotExist:
                        logger.debug(u"%s" %
                                     (_('Exception caught, UserDoesNotExist')))
                        # Create a new user. Note that we can set password
                        # to anything, because it won't be checked; the
                        # password from settings.py will.
                        user = User(username=username,
                                    password=current_user.password,
                                    is_staff=current_user.is_staff,
                                    is_superuser=current_user.is_superuser)
                        user.save()
                    return user
                else:
                    logger.info(u"%s %s %s" %
                                (_('User'), current_mocambola,
                                 _('doesn\'t exist or password is wrong!')))
                    return None
                return True
            # fim do if
        # fim do for
        return None