from functools import wraps
from codes import HTTPStatus, APIStatus, ErrorMessage, EmailCredentials
from models import StaffUser as User
from django.shortcuts import redirect
from django.http import HttpResponse
import urllib
import urllib2
from contextlib import closing

def authenticate_user(function):
    @wraps(function)
    def wrapper(request, *args, **kw):
        out_msg = {"status": APIStatus.ERROR, "msg": ErrorMessage.DEFAULT_ERROR}
        status = ""
        try:
            user_id = request.user.ph_number
            if not user_id:
                out_msg["msg"] = ErrorMessage.AUTHORIZATION_MISSING
                status = HTTPStatus.NOT_AUTHORIZED
            else:
                user_obj = User.objects.get(user__id=request.user.id)
                if not user_obj:
                    out_msg["msg"] = ErrorMessage.USER_NOT_FOUND
                    status = HTTPStatus.USER_NOT_ALLOWED
                if not user_obj.user.is_active:
                    return redirect('login')
                else:
                    return redirect('home')

        except Exception, ex:
            out_msg["msg"] = str(ex)
            status = HTTPStatus.INTERNAL_SERVER_ERROR

        if status:
            return make_response(msg=out_msg, status=status)

        return function(*args, **kw)
    return wrapper


def make_response(msg, status=200, mime='application/json'):
    import json
    msg = json.dumps(msg)
    response_data = {'status': status, 'message': msg, 'mimetype': mime}
    print response_data
    print response_data['status']
    if response_data['status'] == HTTPStatus.NOT_AUTHORIZED:
        return redirect('login')
    return HttpResponse(json.dumps(response_data), content_type="application/json")



def send_email( recipient, subject, body):
    import smtplib

    gmail_user = EmailCredentials.SENDER_EMAIL
    gmail_pwd = EmailCredentials.SENDER_PASSWORD
    FROM = EmailCredentials.SENDER_EMAIL
    TO = recipient if type(recipient) is list else [recipient]
    SUBJECT = subject
    TEXT = body

    # Prepare actual message
    message = """From: %s\nTo: %s\nSubject: %s\n\n%s
    """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
    try:
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.ehlo()
        server.starttls()
        server.login(gmail_user, gmail_pwd)
        server.sendmail(FROM, TO, message)
        server.close()
        print ('successfully sent the mail')
        return True
    except:
        print ("fai led to send mail")
        return False





def send_sms(number, message):
    # number = '923362227908'
    # message = "You have successfully logged in to Dessange mobile app on " + datetime.datetime.now().strftime(
    #     '%Y-%mm-%d %I:%M %p') + ""

    #print(number)

    url = 'http://fastsmsalerts.com/quicksms?action=compose&id=figure&pass=@987654321&mask=Dessange&to=' \
          + number + '&portable=&lang=english&' + urllib.urlencode(
        {"msg": message}) + '&type=json'

    #print(url)

    with closing(urllib.urlopen(url)) as response:
        print(str(response.read()))

ed71010f5a8dd41fa29c23cba165fa956d5827fb
from functools import wraps
from codes import HTTPStatus, APIStatus, ErrorMessage, EmailCredentials
from models import StaffUser as User
from django.shortcuts import redirect
from django.http import HttpResponse
import urllib
import urllib2
from contextlib import closing

def authenticate_user(function):
    @wraps(function)
    def wrapper(request, *args, **kw):
        out_msg = {"status": APIStatus.ERROR, "msg": ErrorMessage.DEFAULT_ERROR}
        status = ""
        try:
            user_id = request.user.ph_number
            if not user_id:
                out_msg["msg"] = ErrorMessage.AUTHORIZATION_MISSING
                status = HTTPStatus.NOT_AUTHORIZED
            else:
                user_obj = User.objects.get(user__id=request.user.id)
                if not user_obj:
                    out_msg["msg"] = ErrorMessage.USER_NOT_FOUND
                    status = HTTPStatus.USER_NOT_ALLOWED
                if not user_obj.user.is_active:
                    return redirect('login')
                else:
                    return redirect('home')

        except Exception, ex:
            out_msg["msg"] = str(ex)
            status = HTTPStatus.INTERNAL_SERVER_ERROR

        if status:
            return make_response(msg=out_msg, status=status)

        return function(*args, **kw)
    return wrapper


def make_response(msg, status=200, mime='application/json'):
    import json
    msg = json.dumps(msg)
    response_data = {'status': status, 'message': msg, 'mimetype': mime}
    print response_data
    print response_data['status']
    if response_data['status'] == HTTPStatus.NOT_AUTHORIZED:
        return redirect('login')
    return HttpResponse(json.dumps(response_data), content_type="application/json")



def send_email( recipient, subject, body):
    import smtplib

    gmail_user = EmailCredentials.SENDER_EMAIL
    gmail_pwd = EmailCredentials.SENDER_PASSWORD
    FROM = EmailCredentials.SENDER_EMAIL
    TO = recipient if type(recipient) is list else [recipient]
    SUBJECT = subject
    TEXT = body

    # Prepare actual message
    message = """From: %s\nTo: %s\nSubject: %s\n\n%s
    """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
    try:
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.ehlo()
        server.starttls()
        server.login(gmail_user, gmail_pwd)
        server.sendmail(FROM, TO, message)
        server.close()
        print ('successfully sent the mail')
        return True
    except:
        print ("fai led to send mail")
        return False





def send_sms(number, message):
    # number = '923362227908'
    # message = "You have successfully logged in to Dessange mobile app on " + datetime.datetime.now().strftime(
    #     '%Y-%mm-%d %I:%M %p') + ""

    #print(number)

    url = 'http://fastsmsalerts.com/quicksms?action=compose&id=figure&pass=@987654321&mask=Dessange&to=' \
          + number + '&portable=&lang=english&' + urllib.urlencode(
        {"msg": message}) + '&type=json'

    #print(url)

    with closing(urllib.urlopen(url)) as response:
        print(str(response.read()))
