class ForgotController(BaseController):
    # Uncomment this line if your controller requires an authenticated user
    # allow_only = predicates.not_anonymous()
    
    def __init__(self):
        dh = LogDBHandler( config=config,request=request);        
        log.addHandler(dh)
        
        self.utility = Utility();
        self.urlServer =  model.SystemEnvironment.getServerUrl();
        
    @expose('json'  )
    def index(self,**kw):
        
        self.email = kw.get('email');
        
        self.user = model.User.by_email_address(self.email);
        if(self.user):
            newPassword = self.utility.id_generator(8);
            #self.user._set_password(newPassword);
            
            self.emailValues={};
            self.emailValues['user_name'] = self.user.user_name;
            self.emailValues['email'] = self.user.email_address;
            self.emailValues['password'] = newPassword;
             
            self.sendMailService = SendMailService();
            self.sendMailService.sendForgotPassword(self.emailValues);
            self.sendMailService.start();
             
        else:
            log.info('forget password email : %s can not access',self.email);
        redirect("/login")
 def __init__(self, ):
     
     print "init RegisterController"
     self.utility = Utility();  
     self.sendMailService = SendMailService();
     self.registerService = RegisterService();
     
     dh = LogDBHandler( config=config,request=request);        
     log.addHandler(dh)
 def create(self,*args,**kw):
     
     log.info(kw);
     print kw
     print len(kw)
     if len(kw) == 0:
         redirect( '/login')
     
     try:
         self.email = kw.get('email');
         self.password = kw.get('password');
         self.rpassword = kw.get('rpassword');
         
         self.success= True;
         self.message = "create success";
         self.urlServer =  model.SystemEnvironment.getServerUrl();
         
         u = model.User.by_email_address(self.email);
         if u is None:
              
             if( str(self.password) ==  str(self.rpassword) ):
                 
                  
                 self.user,self.userGenCode = self.registerService.createUser(kw);
                 
                 self.emailValues={};
                 self.emailValues['user_name'] = self.user.display_name;
                 self.emailValues['email'] = self.user.email_address;
                 self.emailValues['password'] = self.password;
                 self.emailValues['activate_url'] =  request.scheme   + '://' + self.urlServer + "/activate/value/" + str(self.userGenCode.code);  #request.application_url
                 
                 self.sendMailService = SendMailService();
                 self.sendMailService.sendActivate(self.emailValues);
                 self.sendMailService.start();
                     
                 log.info("create user : %s " , self.email);
                 
                 
             else:
                 self.message ="password not same";
                 self.success= False;
                 log.info("password not same : %s " , self.email);
              
         else:
             self.message = "email have already";
             self.success= False;
             log.info("email have already : %s " , self.email);
         u =None;
     except Exception as inst:
         log.error("error : %s " %inst);
         flash(_(LanguageObject.getdata("msg_error_data_register")), 'warning')   
         redirect( '/login')
     return dict(success=self.success, message = self.message);
 def reActivateUser(self,user):
     self.userGenCode = None
     self.user = user
     if(self.user):
         self.userGenCode = self.createUserGenCode(self.user)
         
         self.emailValues={};
         self.emailValues['user_name'] = self.user.display_name;
         self.emailValues['email'] = self.user.email_address;
         self.emailValues['password'] = '';
         self.emailValues['activate_url'] =  request.scheme   + '://' + self.urlServer + "/activate/" + str(self.userGenCode.code);  #request.application_url
         
         self.sendMailService = SendMailService();
         self.sendMailService.sendreActivate(self.emailValues);
         self.sendMailService.start();
     return self.user, self.userGenCode
 def index(self,**kw):
     
     self.email = kw.get('email');
     
     self.user = model.User.by_email_address(self.email);
     if(self.user):
         newPassword = self.utility.id_generator(8);
         #self.user._set_password(newPassword);
         
         self.emailValues={};
         self.emailValues['user_name'] = self.user.user_name;
         self.emailValues['email'] = self.user.email_address;
         self.emailValues['password'] = newPassword;
          
         self.sendMailService = SendMailService();
         self.sendMailService.sendForgotPassword(self.emailValues);
         self.sendMailService.start();
          
     else:
         log.info('forget password email : %s can not access',self.email);
     redirect("/login")
    def deactivate(self):
        self.user = request.identity["user"]
        self.user.active = 0
        # user.deactivate()

        self.urlServer = model.SystemEnvironment.getServerUrl()
        self.userGenCode = self.registerService.deActivateUserGenCode(self.user)

        self.emailValues = {}
        self.emailValues["user_name"] = self.user.display_name
        self.emailValues["email"] = self.user.email_address
        self.emailValues["deactivate_url"] = (
            request.scheme + "://" + self.urlServer + "/activate/canceldeactive/" + str(self.userGenCode.code)
        )
        # request.application_url

        self.sendMailService = SendMailService()
        self.sendMailService.senddeActivate(self.emailValues)
        self.sendMailService.start()

        # model.User.deactivate()
        flash(_(LanguageObject.getdata("msg_thank_you")), "warning")
        redirect("/logout_handler")
class RegisterService(object):

    def __init__(self):
        print "init RegisterService"
        self.urlServer =  model.SystemEnvironment.getServerUrl();
        self.utility = Utility();
        pass;
    
    def insertOrUpdateUserWithFacebook(self,user,fuser,accessToken):
        self.fullname = fuser['first_name']
        self.fulllastname = fuser['last_name']
        self.email =fuser['email']
        self.tnc = 1
        self.id_gender =  model.Gender.getIdGender(fuser['gender'])
        self.displayname  =  fuser['name']
        self.provider_user_id = fuser['id']
        self.access_token = accessToken['accessToken']
        self.profile_url =fuser['link']  
        self.expiresin = str(accessToken['expiresIn']) 
        self.singed_request = accessToken['signedRequest'] 
        
        locale = self.utility.spritValue(fuser['locale'], '_')
        self.language =  locale[0]
        self.country =  locale[1]
        
        self.insert = False;
        if(user is None):
            user = model.User()
            self.insert= True;
        user.user_name  = self.email
        user.email_address =  self.email
        user.display_name = self.displayname
        
        if(self.insert ):    
            user.save()
        
        self.user_id = user.user_id
        
        
        self.userservice = model.UserService.getByUserId(self.user_id)
        self.usersocial = model.UserSocialNetwork.getByUserIdAndSocialId(self.user_id, '1');  
        
        if(self.userservice is None):
            self.userservice = model.UserService();
            self.insert= True;
            
        self.userservice.user_name = self.email;
        self.userservice.email_address = self.email;
        self.userservice.display_name =  self.displayname ;
        #self.user._set_password(self.password); 
        self.userservice.first_name = self.fullname
        self.userservice.last_name = self.fulllastname
        #self.user.address =self.address
        #self.user.city =self.city
        #self.user.country = self.country
        self.userservice.id_gender = self.id_gender
        self.userservice.accept_tnc = self.tnc
        self.userservice.language = self.language
        self.userservice.country = self.country
        self.userservice.user_id = self.user_id
        
        if(self.insert ):
            self.userservice.save();
            self.userservice.updateGroupUserVoter();
        
        
        if (self.usersocial is None):
            self.usersocial = model.UserSocialNetwork();        
            self.insert= True;
            
               
        self.usersocial.user_id = self.user_id
        self.usersocial.id_social_type = 1
        self.usersocial.provider_user_id = self.provider_user_id
        self.usersocial.access_token = self.access_token
        
        self.usersocial.display_name = self.displayname 
        self.usersocial.profile_url =self.profile_url
        
        self.usersocial.expiresin =  self.expiresin 
        self.usersocial.singed_request = self.singed_request
        
        if(self.insert ):
            self.usersocial.save()
        
        
        return user;
        
    def createUserWithFacebook(self,fuser,accessToken):
        
        self.fullname = fuser['first_name']
        self.fulllastname = fuser['last_name']
        self.email =fuser['email']
        self.tnc = 1
        self.id_gender =  model.Gender.getIdGender(fuser['gender'])
        
        
        locale = self.utility.spritValue(fuser['locale'], '_')
        
        
        user = model.User()
        user.user_name  = self.email
        user.email_address =  self.email
        user.display_name = fuser['name']
        user.save()
        
        
        self.userservice = model.UserService();
        self.userservice.user_name = self.email;
        self.userservice.email_address = self.email;
        self.userservice.display_name =  fuser['name'];
        #self.user._set_password(self.password); 
        self.userservice.first_name = self.fullname
        self.userservice.last_name = self.fulllastname
        #self.user.address =self.address
        #self.user.city =self.city
        #self.user.country = self.country
        self.userservice.id_gender = self.id_gender;
        self.userservice.accept_tnc = self.tnc
        self.userservice.language = locale[0]
        self.userservice.country = locale[1]
        self.userservice.user_id = user.user_id        
        self.userservice.save();
        self.userservice.updateGroupUserVoter();
        
        
        self.usersocial = model.UserSocialNetwork();        
        self.usersocial.user_id = user.user_id
        self.usersocial.id_social_type = 1
        self.usersocial.provider_user_id = fuser['id']
        self.usersocial.access_token = accessToken['accessToken']
        
        self.usersocial.display_name = fuser['name']
        self.usersocial.profile_url =fuser['link']  
        
        self.usersocial.expiresin =  str(accessToken['expiresIn'])  
        self.usersocial.singed_request = accessToken['signedRequest']
        self.usersocial.save()
        
        
         
    
    def createUser(self, kw):
        
        self.registerObject = RegisterObject(**kw);
        
        self.user = self.registerObject.getUser()
        self.user.save(); 
        
        self.userservice = self.registerObject.getUserService();
        self.userservice.user_id = self.user.user_id
        self.userservice.accept_tnc = self.utility.convertToBit(self.userservice.accept_tnc);
        self.userservice.save();
        
        self.userservice.updateGroupUserVoter()
        self.userservice.updateGroupUserCreator()
        
        self.userGenCode = self.createUserGenCode(self.user);
        
        return self.user,self.userGenCode;
    
    def createUserGenCode(self,user):
        self.userGenCode = model.UserGenCode();
        self.userGenCode.user_id =  user.user_id;
        self.userGenCode.id_gen_code_type = 2 ;# register
        self.userGenCode.code = str(self.userGenCode.user_id)+ self.utility.my_random_string(15);
        self.userGenCode.expire_date =  self.utility.plusDate(datetime.today(),30);
        self.userGenCode.save();
        
        return self.userGenCode;
    
    def reActivateUserGenCode(self,userGenCode,user):
        if(userGenCode):
            self.userGenCode = userGenCode;
            
            self.userGenCode.code = str(self.userGenCode.user_id)+ self.utility.my_random_string(15);
            self.userGenCode.expire_date =  self.utility.plusDate(datetime.today(),30);
            self.userGenCode.create_date = datetime.today();
            self.userGenCode.count = self.userGenCode.count +1;
            self.userGenCode.success = 0;
            return self.userGenCode;
        
        return userGenCode;
    
    def deActivateUserGenCode(self,user):
        self.userGenCode = model.UserGenCode()
        self.userGenCode.user_id =  user.user_id
        self.userGenCode.id_gen_code_type = 6 ;# deactivate
        self.userGenCode.code = str(self.userGenCode.user_id)+ self.utility.my_random_string(15)
        self.userGenCode.expire_date =  self.utility.plusDate(datetime.today(),30)
        self.userGenCode.success = 1
        self.userGenCode.save()
        
        return self.userGenCode;
    def reActivateUser(self,user):
        self.userGenCode = None
        self.user = user
        if(self.user):
            self.userGenCode = self.createUserGenCode(self.user)
            
            self.emailValues={};
            self.emailValues['user_name'] = self.user.display_name;
            self.emailValues['email'] = self.user.email_address;
            self.emailValues['password'] = '';
            self.emailValues['activate_url'] =  request.scheme   + '://' + self.urlServer + "/activate/" + str(self.userGenCode.code);  #request.application_url
            
            self.sendMailService = SendMailService();
            self.sendMailService.sendreActivate(self.emailValues);
            self.sendMailService.start();
        return self.user, self.userGenCode
class RegisterController(BaseController):
    """
    The root controller for the PollandSurvey application.

    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.

    """
    
    def __init__(self, ):
        
        print "init RegisterController"
        self.utility = Utility();  
        self.sendMailService = SendMailService();
        self.registerService = RegisterService();
        
        dh = LogDBHandler( config=config,request=request);        
        log.addHandler(dh)

    def _before(self, *args, **kw):
        tmpl_context.project_name = "pollandsurvey"

    @expose('pollandsurvey.templates.register.index')
    def index(self, *args, **kw):
        """Handle the front-page."""
        return dict(page='index')

       
    @expose('json')
    @expose('pollandsurvey.templates.register.register_success')
    def create(self,*args,**kw):
        
        log.info(kw);
        print kw
        print len(kw)
        if len(kw) == 0:
            redirect( '/login')
        
        try:
            self.email = kw.get('email');
            self.password = kw.get('password');
            self.rpassword = kw.get('rpassword');
            
            self.success= True;
            self.message = "create success";
            self.urlServer =  model.SystemEnvironment.getServerUrl();
            
            u = model.User.by_email_address(self.email);
            if u is None:
                 
                if( str(self.password) ==  str(self.rpassword) ):
                    
                     
                    self.user,self.userGenCode = self.registerService.createUser(kw);
                    
                    self.emailValues={};
                    self.emailValues['user_name'] = self.user.display_name;
                    self.emailValues['email'] = self.user.email_address;
                    self.emailValues['password'] = self.password;
                    self.emailValues['activate_url'] =  request.scheme   + '://' + self.urlServer + "/activate/value/" + str(self.userGenCode.code);  #request.application_url
                    
                    self.sendMailService = SendMailService();
                    self.sendMailService.sendActivate(self.emailValues);
                    self.sendMailService.start();
                        
                    log.info("create user : %s " , self.email);
                    
                    
                else:
                    self.message ="password not same";
                    self.success= False;
                    log.info("password not same : %s " , self.email);
                 
            else:
                self.message = "email have already";
                self.success= False;
                log.info("email have already : %s " , self.email);
            u =None;
        except Exception as inst:
            log.error("error : %s " %inst);
            flash(_(LanguageObject.getdata("msg_error_data_register")), 'warning')   
            redirect( '/login')
        return dict(success=self.success, message = self.message);
    
    @expose('pollandsurvey.templates.register.register_success')
    def registerSuccess(self,*args,**kw):
        
        return dict(page='register_success')
    
    
    @expose( )
    def checkUserEmail(self,*args,**kw):
        
        self.email = kw.get('email');
        u = model.User.by_email_address(self.email);
        if u is None:
            return "true";
        return "false";
    
    
    @expose()
    #@validate(RegisterForm, error_handler=index)    
    def create_old(self,*args,**kw):
        
        return str(kw);
        flash(_('Wrong credentials'), 'warning')
        email =  kw['registerform:email_address'];
        user = kw['registerform:user_name'];
        confirm_password =  kw['registerform:confirm_password'];
        user_id = kw['registerform:user_id'];
        display = kw['registerform:display_name'];
        password = kw['registerform:password'];
        
        #u = model.User();
        msg ="";
        u = model.User.by_email_address(email);
        if u is None:
            u = model.User.by_user_name(user);
            if u is None:
                log.info("password : "******" , confirm password : "******"same password")
                    u= model.User();
                    u.user_name = user
                    u.display_name = display
                    u.email_address = email
                    u.password = password
                    
                    
                    #model.DBSession.add(u)
                    model.DBSession.flush()
                    log.info( "save user success");
                else:
                    msg ="password not same";
                    log.info( "password not same");
            else:
                msg = "user have already";
                log.info( "user have already");
        else:
            msg = "email have already";
            log.info( "email have already");
class AccountController(BaseController):
    def __init__(self):
        self.utility = Utility()
        self.registerService = RegisterService()
        dh = LogDBHandler(config=config, request=request)
        log.addHandler(dh)

        self.__getMasterData()

    def _before(self, *args, **kw):
        tmpl_context.project_name = "pollandsurvey"

    def __getMasterData(self):
        self.serviceType = model.SocialType.getAll(1)

    @expose("pollandsurvey.templates.account.index")
    @require(predicates.not_anonymous())
    def index(self, *args, **kw):

        userService = model.UserService()
        if request.identity:
            user = request.identity["user"]
            userService = model.UserService.getById(user.user_id)
            if userService is None:
                userService = model.UserService()

        listConutry = []
        self.country = model.FixCountry.getAll("1")
        for lang in self.country:
            listConutry.append(lang.to_json())

        listGender = model.Gender.getAll(1)
        listLanguage = []

        self.language = model.FixLanguage.getAll("1")
        for lang in self.language:
            listLanguage.append(lang.to_json())

        return dict(
            page="index",
            userService=userService,
            listConutry=listConutry,
            listGender=listGender,
            listLanguage=listLanguage,
        )

    @expose("pollandsurvey.templates.account.changepassword")
    @require(predicates.not_anonymous())
    def changepass(self, *args, **kw):
        """Handle the front-page."""
        return dict(page="changepassword")

    @expose("pollandsurvey.templates.account.socialmedia")
    @require(predicates.not_anonymous())
    def socialmedia(self, *args, **kw):
        user = request.identity["user"]
        self.userSocialNetwork = model.UserSocialNetwork.getSocialByUserId(user.user_id)
        return dict(page="socialmedia", userSocialNetwork=self.userSocialNetwork, socialType=self.serviceType)

    @expose("pollandsurvey.templates.account.cancellation")
    @require(predicates.not_anonymous())
    def cancellation(self, *args, **kw):
        """Handle the front-page."""
        return dict(page="cancellation")

    @expose()
    @require(predicates.not_anonymous())
    def deactivate(self):
        self.user = request.identity["user"]
        self.user.active = 0
        # user.deactivate()

        self.urlServer = model.SystemEnvironment.getServerUrl()
        self.userGenCode = self.registerService.deActivateUserGenCode(self.user)

        self.emailValues = {}
        self.emailValues["user_name"] = self.user.display_name
        self.emailValues["email"] = self.user.email_address
        self.emailValues["deactivate_url"] = (
            request.scheme + "://" + self.urlServer + "/activate/canceldeactive/" + str(self.userGenCode.code)
        )
        # request.application_url

        self.sendMailService = SendMailService()
        self.sendMailService.senddeActivate(self.emailValues)
        self.sendMailService.start()

        # model.User.deactivate()
        flash(_(LanguageObject.getdata("msg_thank_you")), "warning")
        redirect("/logout_handler")

    @expose()
    @require(predicates.not_anonymous())
    def updateprofile(self, *args, **kw):

        if request.identity:

            self.user = request.identity["user"]
            self.userService = model.UserService.getById(self.user.user_id)
            if self.userService is None:
                self.userService = model.UserService()
            self.userService.updateByValue(**kw)
            self.userService.accept_tnc = 1
            self.userService.user_id = self.user.user_id
            self.userService.birthdate = self.utility.convertToDateTime(self.userService.birthdate, "%d/%m/%Y")
            self.userService.updateall()

            flash(_(LanguageObject.getdata("msg_save_success")), "warning")
        else:

            log.warning("user cannot login, redirect to login")
            flash(_(LanguageObject.getdata("msg_not_login")), "warning")

        redirect("/account")

    @expose()
    # @expose('json')
    # @expose('json',content_type="text/plain"  )
    @require(predicates.not_anonymous())
    def rechangepass(self, *args, **kw):

        self.success = False
        self.message = ""
        if request.identity:
            self.current_password = kw.get("password")
            self.new_password = kw.get("newpassword")
            self.re_new_password = kw.get("rnewpassword")
            user = request.identity["user"]

            if user.validate_password(self.current_password):
                if str(self.new_password) == str(self.re_new_password):
                    user._set_password(self.new_password)
                    self.success = True
                    self.message = LanguageObject.getdata("msg_password_changed")
                else:
                    self.message = LanguageObject.getdata("msg_password_not_match")

            else:
                log.warning("user %s password not match : %s", user.user_name, self.current_password)
                self.message = LanguageObject.getdata("msg_password_not_match")
        else:
            self.message = LanguageObject.getdata("msg_not_login")
            log.warning("user cannot login, redirect to login")

        flash(_(self.message), "warning")
        # return dict(success=self.success, message = self.message);

        redirect("/account/changepass")