cowboy添加验证码
参考的http://beebole.com/blog/erlang/how-to-implement-captcha-in-erlang-web-application/,移到cowboy,修改了下;废话不多说,直接贴代码
注意,需要cowboy版本1.0.1
需要imagemagick
sudo apt-get install imagemagick
mac
brew install imagemagick
mac下如果使用convert命令找不到字体,则需要安装下这个
brew install ghostscript
创建工程
rebar-creator create-app testCaptcha
testCaptcha_app
-module(testCaptcha_app). -behaviour(application). -export([start/, stop/]). -define(C_ACCEPTORS, ). start(_StartType, _StartArgs) -> simple_captcha_ets:init(), application:start(crypto),
application:start(cowlib),
application:start(ranch),
application:start(cowboy), Routes = route_helper:get_routes(),
Dispatch = cowboy_router:compile(Routes),
Port = ,
TransOpts = [{port, Port}],
ProtoOpts = [{env, [{dispatch, Dispatch}]}],
cowboy:start_http(http, ?C_ACCEPTORS, TransOpts, ProtoOpts). stop(_State) ->
simple_captcha_ets:destroy(),
ok.
route_helper
-module(route_helper). -export([get_routes/]). get_routes() ->
[
{'_', [
{"/captcha", captcha_handler, []},
{"/captcha_check", captcha_check_handler, []}
]}
].
simple_captcha
-module(simple_captcha). -export([create/,check/]). create() ->
CryptKey = mochihex:to_hex(crypto:rand_bytes()),
Code = generate_rand(), FileName = lists:flatmap(fun(Item) -> integer_to_list(Item) end, tuple_to_list(now())),
File = io_lib:format("/tmp/~s.png",[FileName]), Cmd = io_lib:format("convert -background 'none' -fill '#222222' -size 175 -gravity Center -wave 5x100 -swirl 50 -font DejaVu-Serif-Book -pointsize 28 label:~s -draw 'Bezier 10,40 50,35 100,35 150,35 200,50 250,35 300,35' ~s", [Code, File]),
os:cmd(Cmd), {ok, BinPng} = file:read_file(File),
file:delete(File), simple_captcha_ets:insert(Code,CryptKey), {erlang:list_to_bitstring(CryptKey),BinPng}. check(CryptKeyBitString,CodeBitString) ->
CryptKey = erlang:bitstring_to_list(CryptKeyBitString),
Code = erlang:bitstring_to_list(CodeBitString),
CryptKeyFromEts = simple_captcha_ets:find(Code), case string:equal(CryptKeyFromEts,CryptKey) of
true ->
simple_captcha_ets:remove(code),
true;
_ ->
false
end. %private
generate_rand(Length) ->
Now = now(),
random:seed(element(, Now), element(, Now), element(, Now)),
lists:foldl(fun(_I, Acc) -> [do_rand() | Acc] end, [], lists:seq(, Length)). do_rand(R) when R > , R < ; R > , R < ; R > ->
R; do_rand(_R) ->
do_rand( + random:uniform()).
simple_captcha_ets
-module(simple_captcha_ets). -export([init/,insert/,find/,remove/,destroy/]). init()->
TableName = ets:new(simple_captcha, [public,named_table]),
{ok, TableName}. insert(Key,Value) ->
ets:insert(simple_captcha, {Key, Value}),
ok. find(Key) ->
Result = (
try ets:lookup_element(simple_captcha, Key, ) of
Value ->
Value
catch
_:_ ->
""
end
),
Result. remove(Key) ->
try ets:delete(simple_captcha, Key)
catch
_:_ ->
ok
end. destroy()->
try ets:delete(simple_captcha)
catch
_:_ ->
ok
end.
mochihex
自己下载
captcha_handler
-module(captcha_handler). -export([init/]).
-export([handle/]).
-export([terminate/]). init(_Transport, Req, []) ->
{ok, Req, undefined}. handle(Req, State) ->
%CryptKey用于验证的时候用,需本地保存,CapCode为用户提交的数据
%simple_captcha:check(CryptKey, CapCode)
{CryptKey,BinPng} = simple_captcha:create(), Req2 = cowboy_req:set_resp_cookie(<<"cap">>, CryptKey, [{path, <<"/">>}], Req),
{ok, Req3} = cowboy_req:reply(, [{<<"content-type">>, <<"image/png">>}],BinPng, Req2),
{ok, Req3, State}. terminate(_Reason, _Req, _State) ->
ok.
captcha_check_handler
-module(captcha_check_handler). -export([init/]).
-export([handle/]).
-export([terminate/]). init(_Transport, Req, []) ->
{ok, Req, undefined}. handle(Req, State) ->
{CryptKey,_} = cowboy_req:cookie(<<"cap">>, Req,<<"">>),
{ok, PostVals, Req2} = cowboy_req:body_qs(Req),
CaptchaCode = proplists:get_value(<<"captchaCode">>, PostVals), case simple_captcha:check(CryptKey, CaptchaCode) of
true ->
{ok, Req3} = cowboy_req:reply(, [{<<"content-type">>, <<"text/html">>}],<<"ok">>, Req2),
{ok, Req3, State};
_ ->
{ok, Req3} = cowboy_req:reply(, [{<<"content-type">>, <<"text/html">>}],<<"error">>, Req2),
{ok, Req3, State}
end. terminate(_Reason, _Req, _State) ->
ok.
rebar.config
% -*- erlang -*-
{erl_opts, [debug_info]}.
{deps, [
{cowboy,".*", {git, "https://github.com/ninenines/cowboy", {tag,"1.0.1"}}}
]}.
{cover_enabled, true}. {eunit_opts, [verbose, {report,{eunit_surefire,[{dir,"."}]}}]}.
{sub_dirs, ["apps/testCaptcha", "rel"]}.
run.sh
#!/bin/sh
rebar clean;
rebar compile;
erl -pa apps/*/ebin deps/*/ebin -eval "application:start(testCaptcha)."
captcha_test.html
<img src="http://127.0.0.1:8080/captcha" width="" height=""> <form action="http://127.0.0.1:8080/captcha_check" method="post">
<p>captcha<input type="text" name="captchaCode" /></p>
<input type="submit" value="Submit" />
</form>
收工
cowboy添加验证码的更多相关文章
- asp.net添加验证码
1.新建一个aspx页面生成验证码图像 using System; using System.Data; using System.Configuration; using System.Collec ...
- PHPCMS v9 自定义表单添加验证码验证
1. 在 \phpcms\templates\default\formguide\show.html 中添加验证码显示 <input type="text" id=" ...
- Angular企业级开发(9)-前后端分离之后添加验证码
1.背景介绍 团队开发的项目,前端基于Bootstrap+AngularJS,后端Spring MVC以RESTful接口给前端调用.开发和部署都是前后端分离.项目简单部署图如下,因为后台同时采用微服 ...
- PHPCMS v9 自定义表单添加验证码
1. 在 \phpcms\templates\default\formguide\show.html 中添加验证码显示 <input type="text" id=&quo ...
- cas4.2.4 登添加验证码
看了很多添加验证码的博文,唯独没有4.24的 重点看第3条,其余的和别人博文大致相同 1.首先在cas工程的web.xml增加验证码功能的支持 <!-- 验证码功能 --> &l ...
- [phpcms v9]自定义表单添加验证码验证功能
修改 \phpcms\templates\default\formguide\show.html 中添加验证码显示 <input type="text" id=" ...
- 【转】PHPCMS v9 自定义表单添加验证码验证
1. 在 \phpcms\templates\default\formguide\show.html 中添加验证码显示 <input type="text" id=&quo ...
- C# DateTime的11种构造函数 [Abp 源码分析]十五、自动审计记录 .Net 登陆的时候添加验证码 使用Topshelf开发Windows服务、记录日志 日常杂记——C#验证码 c#_生成图片式验证码 C# 利用SharpZipLib生成压缩包 Sql2012如何将远程服务器数据库及表、表结构、表数据导入本地数据库
C# DateTime的11种构造函数 别的也不多说没直接贴代码 using System; using System.Collections.Generic; using System.Glob ...
- cas添加验证码
cas添加验证码,折腾了好久,终于整理好了,很大部分都是借鉴http://binghejinjun.iteye.com/blog/1255293这个的.但是他的有一个很不好的地方就是不能提升验证码错误 ...
随机推荐
- python常见容器属性和方法
`````字符串中反斜杠字符表 转义格式 意义 \' 单引号(') \" 双引号(") \\ 反斜杠(\ ) \n 换行 \r 返回光标至行首 \f 换页 \t ...
- Cuda 9.2 CuDnn7.0 官方文档解读
目录 Cuda 9.2 CuDnn7.0 官方文档解读 准备工作(下载) 显卡驱动重装 CUDA安装 系统要求 处理之前安装的cuda文件 下载的deb安装过程 下载的runfile的安装过程 安装完 ...
- 一年25个里程碑!免疫疗法“战胜”癌症,靠的是实力(5篇Science、6篇Nature )--转载
近几年,免疫疗法的成功使癌症治疗进入了新的时代.无论是科研界,还是商业界,都丝毫没有掩饰对这一领域的热情.2016年,Cell杂志公布的年度十大最佳论文中,免疫疗法占两席.事实上,这两项成果只是去年癌 ...
- 例子.ZC简单.JSP和session
1.环境: Win7x64.E:\ZC_IDE\Eclipse\Windows\eclipse-jee-mars-R-win32__apk__20180122_1457\eclipse.exe.E:\ ...
- SQL Server 查询优化 索引的结构与分类
一.索引的结构 关系型数据库中以二维表来表达关系模型,表中的数据以页的形式存储在磁盘上,在SQL SERVER中,数据页是磁盘上8k的连续空间,那么,一个表的所有数据页在磁盘上是如何组织的呢?分两种情 ...
- 雷林鹏分享:Ruby 多线程
Ruby 多线程 每个正在系统上运行的程序都是一个进程.每个进程包含一到多个线程. 线程是程序中一个单一的顺序控制流程,在单个程序中同时运行多个线程完成不同的工作,称为多线程. Ruby 中我们可以通 ...
- torchnet+VGG16计算patch之间相似度
torchnet+VGG16计算patch之间相似度 torch VGG16 similarity 本来打算使用VGG实现siamese CNN的,但是没想明白怎么使用torchnet对模型进行微调. ...
- Leetcode 53
//经典class Solution { public: int maxSubArray(vector<int>& nums) { ; int maxsum = -INT_MAX; ...
- ASP.NET ValidationSummary 控件
ASP.NET ValidationSummary 控件 Validation 服务器控件 定义和用法 ValidationSummary 控件用于在网页.消息框或在这两者中内联显示所有验证错误的摘要 ...
- LINQ 分页 和存储过程分页
存储过程分页 SELECT * FROM ( SELECT ROW_NUMBER() OVER(ORDER BY CreateDate DESC) AS RowNo, EstateAddress, E ...