Java Groovy Grails 2019. 12. 5. 04:13

RegisterController.groovy

package com.samsung.apolex

import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.core.userdetails.UserDetails
import grails.plugin.springsecurity.ui.RegisterCommand
import com.samsung.apolex.auth.*
import com.samsung.apolex.User
import com.samsung.apolex.Authority
import com.samsung.apolex.UserAuthority
import groovy.json.JsonSlurper;
import grails.converters.JSON
import groovy.json.JsonBuilder
import javax.servlet.http.Cookie
import grails.config.Config

class RegisterController extends grails.plugin.springsecurity.ui.RegisterController {
	
	static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
	static defaultAction = 'register'

	Config config = grailsApplication.config
	def api_server_ip= config.getRequiredProperty('server_info.api_server_ip')
	def port_number= config.getRequiredProperty('server_info.port_number')	

	UserDetailsService userDetailsService

	def register()
	{
		respond new User(params)
	}

	def complete(User user){
	  if (params.username && params.password && params.confirm && params.email && params.memo){
		if (User.findByUsername(params.username)){
			flash.message="ERROR: username exists"
			redirect(action:"register", params:params)
			return
		}
		else if (params.password.equals(params.confirm)){
				def role = Authority.findByAuthority("ROLE_ADMIN")
				def newuser = new User(params).save(flush:true)
				if (!user.authorities) {
					def userIsARole = new UserAuthority(user: newuser, authority: role)
					userIsARole.save()		
				}
				
				flash.message="User("+params.username+") is created."
				def status=registerToWP(params.username, params.password, params.email, params.memo)
				if (status=="ok"){
					flash.message+=" WP user is also created with same id"
				}
				else{
					flash.message+=" WP user creation is failed. Ask admin to resolve the issue." 
				}
				redirect(controller:"login", action:"auth")
							
		} 
		else{
			flash.error="ERROR: passwords are NOT same. try again"
			redirect(action:"register", params:params)	
		}
	  }
	  else {
		flash.message="* All fields are required."
		redirect(action:"register", params:params)	
	  }
	}

	def getNonceForRegistration(){
			def JSONURL="http://"+api_server_ip+port_number+"/static/wp/api/get_nonce/?controller=user&method=register"
			println JSONURL
			
			def jsonText = ""
			try{
				jsonText=JSONURL.toURL().getText(connectTimeout: 30000, readTimeout: 60000, requestProperties: [Accept: 'application/json'])
			}
			catch (e){
				flash.message="Not found(nonce)"
				return
			}

			JsonSlurper jsonSlurper = new JsonSlurper();
			Object result = jsonSlurper.parseText(jsonText);
	 
			Map jsonResult = (Map) result;
			String status = (String) jsonResult.get("status");
			String nonce = (String) jsonResult.get("nonce");
			
			if (status=="ok" && nonce){
				return nonce
			} else{
				return ""
			}
	}

	def test_get_nonce(){
		render getNonceForRegistration()
	}
	def test_gen_wp_cookie(){
		def username="samsung666"
		def password="samsung666"
		get_wp_cookie(username, password)
	}

	def registerToWP(String username, String password, String email, String name){
			String nonce = getNonceForRegistration()
			
			def now = new Date().format("YYYYMMdd-HH-mm-ss") // avoid existing email error
			def no_space_name=name.replaceAll(" ", "_")
			
			def JSONURL="http://"+api_server_ip+port_number+"/static/wp/api/user/register?" +
						"nonce=" + nonce +
						"&insecure=cool" +
						"&notify=no" +
						"&username=" + username +
						"&user_pass=" + password +
						"&email=" + now +"-"+email +
						"&display_name=" + no_space_name
						
			println JSONURL
			
			def jsonText = ""
			try{
				jsonText=JSONURL.toURL().getText(connectTimeout: 30000, readTimeout: 60000, requestProperties: [Accept: 'application/json'])
			}
			catch (e){
				flash.message="Not found(nonce)"
				return
			}

			JsonSlurper jsonSlurper = new JsonSlurper()
			Object result = jsonSlurper.parseText(jsonText)
	 
			Map jsonResult = (Map) result;
			String status = (String) jsonResult.get("status");
			
			return status
	}

	// this cookie works only WP is on the same server
	//
	def get_wp_cookie(String username, String password){ // will not work in server-side. use client-side javascript version
			def JSONURL="http://"+api_server_ip+port_number+"/static/wp/api/user/generate_auth_cookie/?insecure=cool&username="+username+"&password="+password
			println JSONURL
			
			def jsonText = ""
			try{
				jsonText=JSONURL.toURL().getText(connectTimeout: 30000, readTimeout: 60000, requestProperties: [Accept: 'application/json'])
			}
			catch (e){
				flash.message="WP autologin failed. (WP username is not found)"
				return
			}

			JsonSlurper jsonSlurper = new JsonSlurper()
			Object result = jsonSlurper.parseText(jsonText)
	 
			Map jsonResult = (Map) result;
			String status = (String) jsonResult.get("status")
			if (status=="ok"){
				String gcookie_name = (String) jsonResult.get("cookie_name")
				String gcookie = (String) jsonResult.get("cookie")

				Cookie cookie = new Cookie(gcookie_name,gcookie)
				cookie.maxAge = 100
				
				cookie.setDomain(api_server_ip) // ******* this works only when domain is same as the code is running. Or will be rejected
				cookie.setPath("/")
				response.addCookie(cookie)			
				
				//render 
				println "WP cookie generation is success: "+gcookie_name+"="+gcookie
				return
			} else{
				String error = (String) jsonResult.get("error")
				//render 
				println "WP cookie generation is failed: "+error
				return
			}

			return
	}	

} // RegisterController

 

register.gsp

<html>
<head>
    <meta name="layout" content="main"/>
    <title>SRA-APOLEX User Registeration</title>

    <asset:link rel="icon" href="favicon.ico" type="image/x-ico" />
<style>
.main{
 	margin-top: 5px;
}
/*
h1.title { 
	font-size: 50px;
	font-family: 'Passion One', cursive; 
	font-weight: 400; 
}
*/
hr{
	width: 10%;
	color: #fff;
}

.form-group{
	margin-bottom: 15px;
}

label{
	margin-bottom: 5px;
}

input,
input::-webkit-input-placeholder {
    font-size: 11px;
    padding-top: 0px;
}

.main-login{
 	background-color: #fff;
    /* shadows and rounded borders */
    -moz-border-radius: 2px;
    -webkit-border-radius: 2px;
    border-radius: 2px;
    -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
    -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
    box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);

}

.main-center{
 	margin-top: 10px;
 	margin: 0 auto;
 	max-width: 330px;
    padding: 30px 30px;

}

.login-button{
	margin-top: 5px;
}

.login-register{
	font-size: 11px;
	text-align: center;
}
</style>
</head>
<body>
		<div class="container">
			<div class="row main">
				<div class="panel-heading">
	               <div class="panel-title text-center">
	               		<h1 class="title">SRA APOLEX - Registration</h1>
	               	</div>
	            </div> 
				<div class="main-login main-center">
					<g:form resource="${this.user}"method="post" url="[controller:'register',action:'complete']">
						<g:if test="${flash.message}">
							<div class="message" role="status">${flash.message}</div>
						</g:if>						
						<div class="form-group">
							<label for="username" class="cols-sm-2 control-label">Username *</label>
							<div class="cols-sm-10">
								<div class="input-group">
									<span class="input-group-addon"><i class="fa fa-users fa" aria-hidden="true"></i></span>
									<input type="text" class="form-control" name="username" id="username"  placeholder="Enter your Username"/>
								</div>
							</div>
						</div>

						<div class="form-group">
							<label for="password" class="cols-sm-2 control-label">Password *</label>
							<div class="cols-sm-10">
								<div class="input-group">
									<span class="input-group-addon"><i class="fa fa-lock fa-lg" aria-hidden="true"></i></span>
									<input type="password" class="form-control" name="password" id="password"  placeholder="Enter your Password"/>
								</div>
							</div>
						</div>

						<div class="form-group">
							<!--<label for="confirm" class="cols-sm-2 control-label">Confirm Password *</label>-->
							<div class="cols-sm-10">
								<div class="input-group">
									<span class="input-group-addon"><i class="fa fa-lock fa-lg" aria-hidden="true"></i></span>
									<input type="password" class="form-control" name="confirm" id="confirm"  placeholder="Confirm your Password"/>
								</div>
							</div>
						</div>
						
						<div class="form-group">
							<label for="email" class="cols-sm-2 control-label">Your Email *</label>
							<div class="cols-sm-10">
								<div class="input-group">
									<span class="input-group-addon"><i class="fa fa-envelope fa" aria-hidden="true"></i></span>
									<input type="text" class="form-control" name="email" id="email"  placeholder="Enter your Email"/>
								</div>
							</div>
						</div>


						<div class="form-group">
							<label for="name" class="cols-sm-2 control-label">Your Name *</label>
							<div class="cols-sm-10">
								<div class="input-group">
									<span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"></i></span>
									<input type="text" class="form-control" name="memo" id="memo"  placeholder="Enter your Name"/>
								</div>
							</div>
						</div>

						<div class="form-group ">
							<!--<button type="button" class="btn btn-primary btn-lg btn-block login-button">Register</button>-->
							<g:submitButton class="btn btn-primary btn-lg btn-block login-button" name="complete" value="complete" />
						</div>
						<div class="login-register">
				            <a href="/home">home / login</a>
				         </div>
					</g:form>
				</div>
			</div>
		</div>

</body>
</html>

Required WP plugin: https://www.parorrey.com/solutions/json-api-user/

posted by kimsooil
: