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这个的.但是他的有一个很不好的地方就是不能提升验证码错误 ...
随机推荐
- 初识PHP(一)基础语法
一直准备学习PHP,结果前一段时间总是有事情,耽误了一阵子.现在赶快迎头赶上! 这个系列只是谈谈我对于PHP的一些看法,不是教程性质的.另外我是小白,只是写写随笔,大神求轻拍.本人学习过c .java ...
- 51nod 1042 数字0-9的数量
给出一段区间a-b,统计这个区间内0-9出现的次数. 比如 10-19,1出现11次(10,11,12,13,14,15,16,17,18,19,其中11包括2个1),其余数字各出现1次. Inp ...
- HDU 4745 Two Rabbits(最长回文子序列)
http://acm.hdu.edu.cn/showproblem.php?pid=4745 题意: 有一个环,现在有两只兔子各从一个点开始起跳,一个沿顺时针,另一个沿逆时针,只能在一圈之内跳,并且每 ...
- 图像添加logo水印函数
<?php //图像添加水印函数 /** *为一张图片添加上一个logo水印(以保存新图片的方式实现) *@param string $picname 被缩放的处理图片源 *@param int ...
- BZOJ 3527 【ZJOI2014】 力
题目链接:力 听说这道题是\(FFT\)板子题,于是我就来写了…… 首先可以发现这个式子:\[E_i=\sum_{j<i}\frac{q_j}{(i-j)^2}-\sum_{j>i}\fr ...
- mac 下安装 express
express为js的后端框架, 终端 >>> npm install -g express-generator 然后cd到您要创建项目的目录之下,输入 >>> ...
- 学习gulpfile.babel.js随笔
'use strict' import gulp from 'gulp' //将gulp插件包含进来 import sass from 'gulp-sass' //编译sass文件 import im ...
- Linux命令详解-whatis
描述一个命令执行什么功能. 1.命令格式: whatis [ -M PathName ] Command ... 2.命令功能: 描述一个命令执行什么功能. 3.命令参数: -M PathNa ...
- UVALive 5903 Piece it together 二分匹配,拆点 难度:1
https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_probl ...
- halcon之最小二乘拟合直线
如果不了解最小二乘算法 请先阅读: Least squares的算法细节原理https://en.wikipedia.org/wiki/Least_squares 通常在halcon中拟合直线会用ho ...