IOS学习之IOS端账号密码登入和后台校验方式

这里先列出server后台对登入的方法验证:

<struts>
	<package name="system-remote" extends="default" namespace="/common/open">
		<action name="login" class="net.zdsoft.eis.remote.RemoteAppLoginAction"
			method="login" />
	</package>
</struts>

//移动端参数
	private String parm;

	public void login() throws Exception {
		JSONObject json = getJsonParam();
		boolean permission=true;
		String username = json.getString("username");
		String pwd = json.getString("pwd");
		parm = getParamValue("parm");
		try {
			String ispermission = json.getString("permission");
			if(StringUtils.isNotBlank(ispermission) && "false".equals(ispermission)){
				permission=false;
			}
		} catch (Exception e) {
		}
		
		User user = null;
		Account account = null;
		String errorMsg = null;
		if (isEisDeploy()) {
			try {
				user = userService.getUserByUserName(username);
			} catch (Exception e) {
				errorMsg = "取用户信息出错: " + e.getMessage();
			}
		} else {
			account = baseDataSubsystemService.queryAccountByUsername(username);
			if (account != null) {
				String accountId = account.getId();
				user = userService.getUserByAccountId(accountId);
				user.setPassword(account.getPassword());
			}
		}
		String password = null;
		if (null != user) {
			/** password城域库中密码, pwd为用户输入密码 * */
			password = user.findClearPassword();
			if ("".equals(password)) {
				password = null;
			}
		}

		int result;// 1:用户名密码正确;-1:用户名不存在;-2:密码错误;-3:用户状态不正常
		if (null == user || user.getName() == null) {
			result = -1;
		} else if (user.getMark() == null
				|| user.getMark() != User.USER_MARK_NORMAL) {
			result = -3;// 用户状态不正常(如: 未审核,锁定等)
		} else if ((password == null && (StringUtils.isBlank(pwd)))
				|| pwd.equals(password)) {
			result = 1;
		} else {
			result = -2;
		}

		// 用户校验正常情况下还需校验其所属单位信息是否正常
		if (result == 1) {
			Unit unit = unitService.getUnit(user.getUnitid());
			if (unit == null || unit.getIsdeleted()) {
				errorMsg = "用户所属单位信息不存在或已经删除!";
			} else {
				int mark = unit.getMark().intValue();
				if (Unit.UNIT_MARK_NORAML != mark) {
					errorMsg = "用户所属单位信息未审核或已锁定!";
				}
				// 报送单位
				if (null == unit.getUsetype()) {
					errorMsg = "用户所属单位信息的报送类别为空!";
				}
			}
		} else if (result == -3) {
			errorMsg = "该账号未审核或已锁定,请联系单位管理员或上级单位管理员!";
		} else {
			errorMsg = "账号或密码错误,请重新输入!";
		}
		if (StringUtils.isBlank(errorMsg)) {
			AppLoginUser loginUser = initLoginUser(user,permission);
			sendResult(RemoteCallUtils.convertJson(loginUser).toString());
		} else {
			sendResult(RemoteCallUtils.convertError(errorMsg).toString());
		}
	}
public static final String JSON_PARAM = "params";
/**
     * 取得经过解析后的返回参数
     * @return
     */
    public JSONObject getJsonParam() {
        if (jsonParam != null)
            return jsonParam;
        JSONObject jsonv = getJson();
        if (jsonv.containsKey(RemoteCallUtils.JSON_PARAM)) {
            jsonParam = jsonv.getJSONObject(RemoteCallUtils.JSON_PARAM);
        }
        else {
            jsonParam = new JSONObject();
        }
        return jsonParam;
    }


/**
     * 取得返回的原始参数
     * @return
     */
    public JSONObject getJson() {
        if (json != null)
            return json;
        String param = getRemoteParam();
        param = RemoteCallUtils.decode(remoteParam);
        if (StringUtils.isBlank(param)) {
            return new JSONObject();
        }
        try {
            json = JSONObject.fromObject(param);
            return json;
        }
        catch (Exception e) {
            return new JSONObject();
        }
    }

<pre name="code" class="java">RemoteCallUtils.java 类中的方法
 
/**
     * 内容进行解密以及反编码压缩
     * 
     * @param s
     * @return
     */
    public static String decode(String s) {
        // MD5加密先去掉
        // String md5 = StringUtils.substring(s, 0, 32);
        String zips = ZipUtils.unzipDecode(StringUtils.substring(s, 32));
        // String checkMd5 =
        // SecurityUtils.encodeByMD5(SecurityUtils.encodeByMD5(zips) + zips);
        // if (StringUtils.equals(md5, checkMd5)) {
        // return zips;
        // }
        // else {
        // return "";
        // }
        return zips;
    }
ZipUtils类中的方法
public static String unzipDecode(String encode) {

        byte[] bs;
        try {
            bs = Base64.decodeBase64(encode);
            Inflater decompressor = new Inflater();
            decompressor.setInput(bs);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(bs.length);
            byte[] buf = new byte[1024];
            buf = new byte[1024];
            while (!decompressor.finished()) {
                int count = decompressor.inflate(buf);
                if (count <= 0)
                    break;
                bos.write(buf, 0, count);
            }
            bos.close();
            byte[] decompressedData = bos.toByteArray();
            return new String(decompressedData, "utf8");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

IOS移动端发送账号密码进行校验

#pragma mark - 登录的代理方法
-(void) doLoginWithUserName:(NSString *)userName password:(NSString *) pwd
{
    if ([userName isEqualToString:@""]) {
        // 用户名不能为空
        [MessageTool showMessage:@"请输入用户名"];
        return;
    }
    
    if ([pwd isEqualToString:@""]) {
        // 密码不能为空
        [MessageTool showMessage:@"请输入密码"];
        return;
    }
    
    //NSLog(@"用户名:%@ 密码:%@",userName, pwd);

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    //param: {username:’登陆账号’, pwd:’密码’, parm:’office_mobile’}
    params[kParamKeyUserName] = userName;
    params[kParamKeyUserPwd] = pwd;
    params[kParamKeyMobileParam] = @"office_mobile";

    NSURL *loginUrl = [HttpTool getActionUrl: @"common/open/login.action"];

    [HttpTool method:@"GET" url:loginUrl params:params success:^(id JSON) {
        NSDictionary *dic = (NSDictionary *)JSON;
        if ([dic[kJSON_RESULT_STATUS] integerValue] == JSON_STATUS_SUCCESS) {
            // 登录成功
            //保存帐号
            [[AccountSerive sharedAccountSerive] saveAccount:params];
            [AccountSerive sharedAccountSerive].currentUser = [[LoginUser alloc] initWithDict:dic];
            self.view.window.rootViewController = [[MainController alloc] init];
        } else {
            //登录失败
            [MessageTool showMessage:dic[kJSON_RESULT_STR]];
        }
    } failure:^(NSError *error) {
        [MessageTool showMessage:kHttpErrorMessage];
    }];

}
HttpTool 方法中

+ (void)method:(NSString *)method url:(NSURL *)url params:(NSDictionary *)params success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure
{

    NSURL *newUrl = [NSURL URLWithString:[RemoteCallTool dictToParamString:params] relativeToURL:url];
    
    NSLog(@"url=%@", [newUrl absoluteString]);
    
    if ([[method lowercaseString] isEqualToString:@"get"]) {
        [self GET:newUrl params:nil success:success failure:failure];
    } else {
        [self POST:newUrl params:nil success:success failure:failure];
    }

}
RemoteCallTool类中方法中:

@implementation RemoteCallTool

#pragma mark dict转nsstring 
+(NSString *) dictToParamString:(NSDictionary *) dictionary
{
    NSMutableString *params = [[NSMutableString alloc] init];
 
    [params appendString:@"?"];
    [params appendString:kPARAM_NAME];
    [params appendString:@"="];

    NSMutableDictionary * allParams = [NSMutableDictionary dictionary];
    
    allParams[kJSON_PARAM] = dictionary;
    allParams[kJSON_TASK_ID] = [self uuidString];
    
    NSError* error = nil;
    NSData* result = [NSJSONSerialization dataWithJSONObject:allParams options:kNilOptions error:&error];
    if (error != nil) {
        return nil;
    }
    [params appendString:[self encode:[[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding]]];
    // url中如果包含中文字符,需要转换成带百分号的格式
    return [params stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}


#pragma mark 解码返回的HTTP response
+(id)decodeResponse:(NSData *)responseData
{
    NSString *response = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSString *responseJson = [self decode:response];
    //NSLog(@"response:%@", responseJson);
    return [JsonTool jsonStringToObject:responseJson];
}



+ (NSString *)uuidString
{
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
    NSString *uuid = [NSString stringWithString:(__bridge NSString *)uuid_string_ref];
    CFRelease(uuid_ref);
    CFRelease(uuid_string_ref);
    return [[uuid lowercaseString] stringByReplacingOccurrencesOfString:@"-" withString:@""];
}


#pragma mark 加密字符串
+(NSString *) encode:(NSString *)str
{
    
    //NSString *str =@"{\"result_status\":-1,\"result_str\":\"参数不对!\"}";
    //@"eJyrVipKLS7NKYkvLkksKS1WstI11EEIFSlZKT3tb3o2dcOTHb1P1-98v6dRqRYAGEoXfw";
    
    NSData *zipeData =[CompressTool zlibCompressData:[str dataUsingEncoding:NSUTF8StringEncoding]];
    NSData *base64Data= [GTMBase64 webSafeEncodeData:zipeData padded:NO];
    NSString *encodedStr = [[NSString alloc] initWithData:base64Data  encoding:NSUTF8StringEncoding];
    
    NSString *selfMD5 = [[CryptoTool md5:str] stringByAppendingString:str];
    return [[CryptoTool md5:selfMD5] stringByAppendingString:encodedStr];
}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值