Пример #1
0
def register(request):
    data = json.loads(request.body)
    result = {}

    try:
        try:
            User.objects.get(username=data["username"])
            result["result"] = "error"
            result["message"] = "That username is taken. Try picking another."
        except User.DoesNotExist:
            # create user
            user = User()
            user.username = data["username"]
            user.email = data["email"]
            user.set_password(data["password"])
            user.save()

            # create user profile
            profile = UserProfile(user=user)
            profile.zipcode = data["zipcode"]
            profile.save()

            user = authenticate(username=data["username"], password=data["password"])
            if user is not None:
                if user.is_active:
                    login(request, user)
                    request.user = user

                    # Once we have logged the user in return the serialized response
                    serializer = api.user.UserSerializer(request.user)
                    response = JSONResponse(serializer.data)
                    response.status_code = 201
                    return response

    except IntegrityError:
        result["result"] = "error"
        result["message"] = "A database error occurred."

    response = JSONResponse(result)
    response.status_code = 409
    return response
Пример #2
0
def auth(request):
    data = {}
    input = json.loads(request.body)

    try:
        if request.method == "POST":
            print request.POST
            uname = input.get("username")
            passwd = input.get("password")
            user = authenticate(username=uname, password=passwd)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    request.user = user

                    # Once we have logged the user in return the serialized response
                    serializer = api.user.UserSerializer(request.user)
                    data["result"] = "success"
                    data["message"] = "User logged in."
                    data["user"] = serializer.data
                    return JSONResponse(data)
    except:
        data["result"] = "error"
        data["message"] = "There was an error contacting the database."

        # They did not provide basic authentication
        response = JSONResponse(data)
        response.status_code = 500
        return response

    data["result"] = "error"
    data["message"] = "Incorrect username or password."

    # They did not provide basic authentication
    response = JSONResponse(data)
    response.status_code = 401
    return response